44// TODO: improve types upstream
55/* eslint-disable @typescript-eslint/no-explicit-any */
66
7- import destr from 'destr'
8- import { snakeCase } from 'scule'
97import { pathToFileURL } from 'node:url'
108import { resolveModulePath } from 'exsolve'
119
@@ -17,12 +15,49 @@ type EnvOptions = {
1715
1816function getEnv ( key : string , opts : EnvOptions ) {
1917 const env = opts . env ?? process . env
20- const envKey = snakeCase ( key ) . toUpperCase ( )
21- return destr (
18+ const envKey = toEnvKey ( key )
19+ return parseEnvValue (
2220 env [ opts . prefix + envKey ] ?? env [ opts . altPrefix + envKey ] ,
2321 )
2422}
2523
24+ function toEnvKey ( key : string ) {
25+ return key
26+ . replace ( / ( [ a - z ] ) ( [ A - Z ] ) / g, '$1_$2' )
27+ . replace ( / ( [ A - Z ] + ) ( [ A - Z ] [ a - z ] ) / g, '$1_$2' )
28+ . replace ( / [ - . / \s ] + / g, '_' )
29+ . toUpperCase ( )
30+ }
31+
32+ const JSON_SIGNATURE_RE = / ^ \s * [ " [ { ] | ^ \s * - ? \d { 1 , 16 } (?: \. \d { 1 , 17 } ) ? (?: e [ + - ] ? \d + ) ? \s * $ / i
33+
34+ function parseEnvValue ( value : unknown ) : unknown {
35+ if ( typeof value !== 'string' ) {
36+ return value
37+ }
38+ if ( value [ 0 ] === '"' && value . at ( - 1 ) === '"' && ! value . includes ( '\\' ) ) {
39+ return value . slice ( 1 , - 1 )
40+ }
41+ switch ( value . trim ( ) . toLowerCase ( ) ) {
42+ case 'true' : return true
43+ case 'false' : return false
44+ case 'undefined' : return undefined
45+ case 'null' : return null
46+ case 'nan' : return Number . NaN
47+ case 'infinity' : return Number . POSITIVE_INFINITY
48+ case '-infinity' : return Number . NEGATIVE_INFINITY
49+ }
50+ if ( ! JSON_SIGNATURE_RE . test ( value ) ) {
51+ return value
52+ }
53+ try {
54+ return JSON . parse ( value , ( key , val ) => key === '__proto__' || ( key === 'constructor' && val && typeof val === 'object' && 'prototype' in val ) ? undefined : val )
55+ }
56+ catch {
57+ return value
58+ }
59+ }
60+
2661function _isObject ( input : unknown ) {
2762 return typeof input === 'object' && ! Array . isArray ( input )
2863}
0 commit comments