Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(helper/adapter): improve runtime detection #2846

Merged
merged 4 commits into from
May 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 31 additions & 8 deletions src/helper/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,51 @@ export const env = <T extends Record<string, unknown>, C extends Context = Conte
return runtimeEnvHandlers[runtime]()
}

export const knownUserAgents: Partial<Record<Runtime, 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 as Runtime
}
}
}

// 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'
}

// couldn't detect the runtime
return 'other'
}

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

return userAgent.startsWith(platform)
}