Skip to content

Commit

Permalink
refactor: improve runtime detection
Browse files Browse the repository at this point in the history
use navigator.userAgent to detect runtime

Closes honojs#2717
  • Loading branch information
6km committed May 28, 2024
1 parent 7b182ca commit 400069d
Showing 1 changed file with 30 additions and 8 deletions.
38 changes: 30 additions & 8 deletions src/helper/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,50 @@ export const env = <T extends Record<string, unknown>, C extends Context = Conte
return runtimeEnvHandlers[runtime]()
}

const knownUserAgents: Record<string, string> = {
deno: 'Deno',
bun: 'Bun',
workerd: 'Cloudflare-Workers',
node: 'Node.js',
}

export const getRuntimeKey = (): Runtime => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any

if (global?.Deno !== undefined) {
return 'deno'
}
if (global?.Bun !== undefined) {
return 'bun'
}
if (typeof global?.WebSocketPair === 'function') {
return 'workerd'
// check if the current runtime supports navigator.userAgent
const userAgentSupported =
typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'

// if supported, check the user agent
if (userAgentSupported) {
for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) {
if (checkUserAgentEquals(userAgent)) {
return runtimeKey
}
}
}

// check if running on Edge Runtime
if (typeof global?.EdgeRuntime === 'string') {
return 'edge-light'
}

// check if running on Fastly
if (global?.fastly !== undefined) {
return 'fastly'
}

// userAgent isn't supported before Node v21.1.0; so fallback to the old way
if (global?.process?.release?.name === 'node') {
return 'node'
}

return 'other'
}

export const checkUserAgentEquals = (platform: string) => {
const userAgent = navigator.userAgent

return userAgent.startsWith(platform)
}

0 comments on commit 400069d

Please sign in to comment.