import { filterValues } from "../collections/filter_values.ts";import { withoutAll } from "../collections/without_all.ts";
export interface DotenvConfig { [key: string]: string;}
type StrictDotenvConfig<T extends ReadonlyArray<string>> = & { [key in T[number]]: string; } & DotenvConfig;
type StrictEnvVarList<T extends string> = | Array<Extract<T, string>> | ReadonlyArray<Extract<T, string>>;
type StringList = Array<string> | ReadonlyArray<string> | undefined;
export interface ConfigOptions { path?: string; export?: boolean; safe?: boolean; example?: string; allowEmptyValues?: boolean; defaults?: string; restrictEnvAccessTo?: StringList;}
export interface LoadOptions { envPath?: string; export?: boolean; examplePath?: string; allowEmptyValues?: boolean; defaultsPath?: string; restrictEnvAccessTo?: StringList;}type LineParseResult = { key: string; unquoted: string; interpolated: string; notInterpolated: string;};
type CharactersMap = { [key: string]: string };
const RE_KeyValue = /^\s*(?:export\s+)?(?<key>[a-zA-Z_]+[a-zA-Z0-9_]*?)\s*=[\ \t]*('\n?(?<notInterpolated>(.|\n)*?)\n?'|"\n?(?<interpolated>(.|\n)*?)\n?"|(?<unquoted>[^\n#]*)) *#*.*$/gm;
const RE_ExpandValue = /(\${(?<inBrackets>.+?)(\:-(?<inBracketsDefault>.+))?}|(?<!\\)\$(?<notInBrackets>\w+)(\:-(?<notInBracketsDefault>.+))?)/g;
export function parse( rawDotenv: string, restrictEnvAccessTo: StringList = [],): Record<string, string> { const env: Record<string, string> = {};
let match; const keysForExpandCheck = [];
while ((match = RE_KeyValue.exec(rawDotenv)) != null) { const { key, interpolated, notInterpolated, unquoted } = match ?.groups as LineParseResult;
if (unquoted) { keysForExpandCheck.push(key); }
env[key] = typeof notInterpolated === "string" ? notInterpolated : typeof interpolated === "string" ? expandCharacters(interpolated) : unquoted.trim(); }
const variablesMap = { ...env, ...readEnv(restrictEnvAccessTo) }; keysForExpandCheck.forEach((key) => { env[key] = expand(env[key], variablesMap); });
return env;}
export function configSync( options?: Omit<ConfigOptions, "restrictEnvAccessTo">,): DotenvConfig;export function configSync<TEnvVar extends string>( options: Omit<ConfigOptions, "restrictEnvAccessTo"> & { restrictEnvAccessTo: StrictEnvVarList<TEnvVar>; },): StrictDotenvConfig<StrictEnvVarList<TEnvVar>>;export function configSync(options: ConfigOptions = {}): DotenvConfig { const r = { restrictEnvAccessTo: options.restrictEnvAccessTo }; return loadSync({ ...r, envPath: options.path, examplePath: options.safe ? options.example : undefined, defaultsPath: options.defaults, export: options.export, allowEmptyValues: options.allowEmptyValues, });}
export function loadSync( options?: Omit<LoadOptions, "restrictEnvAccessTo">,): Record<string, string>;export function loadSync<TEnvVar extends string>( options: Omit<LoadOptions, "restrictEnvAccessTo"> & { restrictEnvAccessTo: StrictEnvVarList<TEnvVar>; },): StrictDotenvConfig<StrictEnvVarList<TEnvVar>>;export function loadSync( { envPath = ".env", examplePath = ".env.example", defaultsPath = ".env.defaults", export: _export = false, allowEmptyValues = false, restrictEnvAccessTo = [], }: LoadOptions = {},): Record<string, string> { const conf = parseFileSync(envPath, restrictEnvAccessTo);
if (defaultsPath) { const confDefaults = parseFileSync(defaultsPath, restrictEnvAccessTo); for (const key in confDefaults) { if (!(key in conf)) { conf[key] = confDefaults[key]; } } }
if (examplePath) { const confExample = parseFileSync(examplePath, restrictEnvAccessTo); assertSafe(conf, confExample, allowEmptyValues, restrictEnvAccessTo); }
if (_export) { for (const key in conf) { if (Deno.env.get(key) !== undefined) continue; Deno.env.set(key, conf[key]); } }
return conf;}
export function config( options?: Omit<ConfigOptions, "restrictEnvAccessTo">,): Promise<DotenvConfig>;export function config<TEnvVar extends string>( options: Omit<ConfigOptions, "restrictEnvAccessTo"> & { restrictEnvAccessTo: StrictEnvVarList<TEnvVar>; },): Promise<StrictDotenvConfig<StrictEnvVarList<TEnvVar>>>;export async function config( options: ConfigOptions = {},): Promise<DotenvConfig> { const r = { restrictEnvAccessTo: options.restrictEnvAccessTo }; return await load({ ...r, envPath: options.path, examplePath: options.safe ? options.example : undefined, defaultsPath: options.defaults, export: options.export, allowEmptyValues: options.allowEmptyValues, });}export function load( options?: Omit<LoadOptions, "restrictEnvAccessTo">,): Promise<Record<string, string>>;export function load<TEnvVar extends string>( options: Omit<LoadOptions, "restrictEnvAccessTo"> & { restrictEnvAccessTo: StrictEnvVarList<TEnvVar>; },): Promise<StrictDotenvConfig<StrictEnvVarList<TEnvVar>>>;export async function load( { envPath = ".env", examplePath = ".env.example", defaultsPath = ".env.defaults", export: _export = false, allowEmptyValues = false, restrictEnvAccessTo = [], }: LoadOptions = {},): Promise<Record<string, string>> { const conf = await parseFile(envPath, restrictEnvAccessTo);
if (defaultsPath) { const confDefaults = await parseFile( defaultsPath, restrictEnvAccessTo, ); for (const key in confDefaults) { if (!(key in conf)) { conf[key] = confDefaults[key]; } } }
if (examplePath) { const confExample = await parseFile( examplePath, restrictEnvAccessTo, ); assertSafe(conf, confExample, allowEmptyValues, restrictEnvAccessTo); }
if (_export) { for (const key in conf) { if (Deno.env.get(key) !== undefined) continue; Deno.env.set(key, conf[key]); } }
return conf;}
function parseFileSync( filepath: string, restrictEnvAccessTo: StringList = [],): Record<string, string> { try { return parse(Deno.readTextFileSync(filepath), restrictEnvAccessTo); } catch (e) { if (e instanceof Deno.errors.NotFound) return {}; throw e; }}
async function parseFile( filepath: string, restrictEnvAccessTo: StringList = [],): Promise<Record<string, string>> { try { return parse(await Deno.readTextFile(filepath), restrictEnvAccessTo); } catch (e) { if (e instanceof Deno.errors.NotFound) return {}; throw e; }}
function expandCharacters(str: string): string { const charactersMap: CharactersMap = { "\\n": "\n", "\\r": "\r", "\\t": "\t", };
return str.replace( /\\([nrt])/g, ($1: keyof CharactersMap): string => charactersMap[$1], );}
function assertSafe( conf: Record<string, string>, confExample: Record<string, string>, allowEmptyValues: boolean, restrictEnvAccessTo: StringList = [],) { const currentEnv = readEnv(restrictEnvAccessTo);
const confWithEnv = Object.assign({}, currentEnv, conf);
const missing = withoutAll( Object.keys(confExample), Object.keys( allowEmptyValues ? confWithEnv : filterValues(confWithEnv, Boolean), ), );
if (missing.length > 0) { const errorMessages = [ `The following variables were defined in the example file but are not present in the environment:\n ${ missing.join( ", ", ) }`, `Make sure to add them to your env file.`, !allowEmptyValues && `If you expect any of these variables to be empty, you can set the allowEmptyValues option to true.`, ];
throw new MissingEnvVarsError( errorMessages.filter(Boolean).join("\n\n"), missing, ); }}
function readEnv(restrictEnvAccessTo: StringList) { if ( restrictEnvAccessTo && Array.isArray(restrictEnvAccessTo) && restrictEnvAccessTo.length > 0 ) { return restrictEnvAccessTo.reduce( ( accessedEnvVars: Record<string, string>, envVarName: string, ): Record<string, string> => { if (Deno.env.get(envVarName)) { accessedEnvVars[envVarName] = Deno.env.get(envVarName) as string; } return accessedEnvVars; }, {}, ); }
return Deno.env.toObject();}
export class MissingEnvVarsError extends Error { missing: string[]; constructor(message: string, missing: string[]) { super(message); this.name = "MissingEnvVarsError"; this.missing = missing; Object.setPrototypeOf(this, new.target.prototype); }}
function expand(str: string, variablesMap: { [key: string]: string }): string { if (RE_ExpandValue.test(str)) { return expand( str.replace(RE_ExpandValue, function (...params) { const { inBrackets, inBracketsDefault, notInBrackets, notInBracketsDefault, } = params[params.length - 1]; const expandValue = inBrackets || notInBrackets; const defaultValue = inBracketsDefault || notInBracketsDefault;
return variablesMap[expandValue] || expand(defaultValue, variablesMap); }), variablesMap, ); } else { return str; }}
export function stringify(object: Record<string, string>) { const lines: string[] = []; for (const [key, value] of Object.entries(object)) { let quote;
let escapedValue = value ?? ""; if (key.startsWith("#")) { console.warn( `key starts with a '#' indicates a comment and is ignored: '${key}'`, ); continue; } else if (escapedValue.includes("\n")) { escapedValue = escapedValue.replaceAll("\n", "\\n"); quote = `"`; } else if (escapedValue.match(/\W/)) { quote = "'"; }
if (quote) { escapedValue = escapedValue.replaceAll(quote, `\\${quote}`); escapedValue = `${quote}${escapedValue}${quote}`; } const line = `${key}=${escapedValue}`; lines.push(line); } return lines.join("\n");}