Skip to content

Commit ff25ade

Browse files
committed
fix(runtime): inline transform helper
1 parent 5c5992b commit ff25ade

1 file changed

Lines changed: 54 additions & 3 deletions

File tree

src/runtime/utils/transform.ts

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,59 @@
1-
import { transformEnvVarsInternal } from '../../utils/transform-shared'
2-
31
interface EnvVar { key: string, value: string }
42
type TransformedConfig = Record<string, string | Record<string, unknown>>
53

4+
function toCamelCase(str: string): string {
5+
return str.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase())
6+
}
7+
8+
function getPrefix(key: string): string | null {
9+
const parts = key.split('_')
10+
return parts.length > 1 ? parts[0]! : null
11+
}
12+
13+
function countPrefixes(keys: readonly string[]): Map<string, number> {
14+
const counts = new Map<string, number>()
15+
for (const key of keys) {
16+
const prefix = getPrefix(key)
17+
if (prefix)
18+
counts.set(prefix, (counts.get(prefix) || 0) + 1)
19+
}
20+
return counts
21+
}
22+
23+
function resolveConfigPath(key: string, prefixCounts: Map<string, number>): string[] {
24+
if (key.startsWith('PUBLIC_'))
25+
return ['public', toCamelCase(key.slice(7))]
26+
27+
if (key.startsWith('NUXT_PUBLIC_'))
28+
return ['public', toCamelCase(key.slice(12))]
29+
30+
const prefix = getPrefix(key)
31+
if (prefix && (prefixCounts.get(prefix) || 0) >= 2) {
32+
return [toCamelCase(prefix), toCamelCase(key.slice(prefix.length + 1))]
33+
}
34+
35+
return [toCamelCase(key)]
36+
}
37+
38+
function assignPath<TValue>(target: Record<string, TValue | Record<string, TValue>>, path: string[], value: TValue): void {
39+
if (path.length === 1) {
40+
target[path[0]!] = value
41+
return
42+
}
43+
44+
const [head, ...tail] = path
45+
target[head!] ??= {}
46+
assignPath(target[head!] as Record<string, TValue | Record<string, TValue>>, tail, value)
47+
}
48+
649
export function transformEnvVars(vars: EnvVar[]): TransformedConfig {
7-
return transformEnvVarsInternal(vars) as TransformedConfig
50+
const result: TransformedConfig = {}
51+
const prefixCounts = countPrefixes(vars.map(v => v.key))
52+
53+
for (const { key, value } of vars) {
54+
const path = resolveConfigPath(key, prefixCounts)
55+
assignPath(result as Record<string, string | Record<string, string>>, path, value)
56+
}
57+
58+
return result
859
}

0 commit comments

Comments
 (0)