2023-08-21 06:22:37 +00:00
|
|
|
import type { Context } from '../../context.ts'
|
2023-03-06 12:12:22 +00:00
|
|
|
|
2023-10-27 02:06:21 +00:00
|
|
|
export type Runtime =
|
|
|
|
| 'node'
|
|
|
|
| 'deno'
|
|
|
|
| 'bun'
|
|
|
|
| 'workerd'
|
|
|
|
| 'fastly'
|
|
|
|
| 'edge-light'
|
|
|
|
| 'lagon'
|
|
|
|
| 'other'
|
|
|
|
|
2023-11-12 00:05:54 +00:00
|
|
|
export const env = <T extends Record<string, unknown>, C extends Context = Context<{}>>(
|
2023-10-27 02:06:21 +00:00
|
|
|
c: C,
|
|
|
|
runtime?: Runtime
|
2023-03-31 09:17:45 +00:00
|
|
|
): T & C['env'] => {
|
2023-03-06 12:12:22 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
const global = globalThis as any
|
2023-09-15 09:40:06 +00:00
|
|
|
const globalEnv = global?.process?.env as T
|
|
|
|
|
2023-10-27 02:06:21 +00:00
|
|
|
runtime ??= getRuntimeKey()
|
2023-09-15 09:40:06 +00:00
|
|
|
|
|
|
|
const runtimeEnvHandlers: Record<string, () => T> = {
|
|
|
|
bun: () => globalEnv,
|
|
|
|
node: () => globalEnv,
|
|
|
|
'edge-light': () => globalEnv,
|
|
|
|
lagon: () => globalEnv,
|
|
|
|
deno: () => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
|
|
// @ts-ignore
|
|
|
|
return Deno.env.toObject() as T
|
|
|
|
},
|
|
|
|
workerd: () => c.env,
|
2023-11-08 20:13:09 +00:00
|
|
|
// On Fastly Compute, you can use the ConfigStore to manage user-defined data.
|
2023-09-15 09:40:06 +00:00
|
|
|
fastly: () => ({} as T),
|
|
|
|
other: () => ({} as T),
|
2023-05-02 07:26:39 +00:00
|
|
|
}
|
2023-09-15 09:40:06 +00:00
|
|
|
|
|
|
|
return runtimeEnvHandlers[runtime]()
|
2023-03-06 12:12:22 +00:00
|
|
|
}
|
2023-08-21 06:22:37 +00:00
|
|
|
|
|
|
|
export const getRuntimeKey = () => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
const global = globalThis as any
|
|
|
|
|
2023-09-15 09:40:06 +00:00
|
|
|
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?.__lagon__ !== undefined) return 'lagon'
|
|
|
|
if (global?.process?.release?.name === 'node') return 'node'
|
2023-08-21 06:22:37 +00:00
|
|
|
|
|
|
|
return 'other'
|
|
|
|
}
|