Skip to content

Commit

Permalink
feat: Introduces JSON type to non-public env variables (#757)
Browse files Browse the repository at this point in the history
* Introduces JSON type to non-public env

* Uses json(...) as the directive

* Uses dotenv-expand for var interpolation

---------

Co-authored-by: Craig Slusher <[email protected]>
Co-authored-by: L <[email protected]>
  • Loading branch information
3 people authored Sep 8, 2023
1 parent a124a2b commit 377e0ab
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions cli/plasmo/src/features/env/env-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,25 @@ function cascadeEnv(loadedEnvFiles: LoadedEnvFiles) {
try {
envFileSet.add(name)
const result = dotenvExpand({
ignoreProcessEnv: true,
parsed: dotenv.parse(contents)
})

if (!!result.parsed) {
vLog(`Loaded env from ${name}`)
const resultData = result.parsed || {}

for (const envKey of Object.keys(resultData)) {
for (const [envKey, envValue] of Object.entries(resultData)) {
if (typeof parsed[envKey] === "undefined") {
parsed[envKey] = resultData[envKey]
try {
parsed[envKey] = maybeParseJSON(envValue)
} catch (ex) {
eLog(`Failed to parse JSON directive ${envKey} in ${name}:`, ex.message)
}

// Pass through internal env variables
if (envKey.startsWith(INTERNAL_ENV_PREFIX)) {
process.env[envKey] = resultData[envKey]
process.env[envKey] = envValue
}
}
}
Expand All @@ -77,6 +82,13 @@ function cascadeEnv(loadedEnvFiles: LoadedEnvFiles) {
return parsed
}

const JSON_DIRECTIVE_RE = /^\s*json\((.+)\)\s*$/si

function maybeParseJSON(value: string): any {
const match = value.match(JSON_DIRECTIVE_RE)
return match ? JSON.parse(match[1]) : value
}

export const getEnvFileNames = () => {
const nodeEnv = process.env.NODE_ENV
const flagMap = getFlagMap()
Expand Down

0 comments on commit 377e0ab

Please sign in to comment.