-
-
Notifications
You must be signed in to change notification settings - Fork 446
/
index.ts
57 lines (49 loc) · 1.49 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { Context } from '../../context'
export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other'
export const env = <T extends Record<string, unknown>, C extends Context = Context<{}>>(
c: C,
runtime?: Runtime
): T & C['env'] => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any
const globalEnv = global?.process?.env as T
runtime ??= getRuntimeKey()
const runtimeEnvHandlers: Record<string, () => T> = {
bun: () => globalEnv,
node: () => globalEnv,
'edge-light': () => globalEnv,
deno: () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return Deno.env.toObject() as T
},
workerd: () => c.env,
// On Fastly Compute, you can use the ConfigStore to manage user-defined data.
fastly: () => ({} as T),
other: () => ({} as T),
}
return runtimeEnvHandlers[runtime]()
}
export const getRuntimeKey = () => {
// 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'
}
if (typeof global?.EdgeRuntime === 'string') {
return 'edge-light'
}
if (global?.fastly !== undefined) {
return 'fastly'
}
if (global?.process?.release?.name === 'node') {
return 'node'
}
return 'other'
}