envalid
Version:
Validation for your environment variables
99 lines • 4.01 kB
JavaScript
import { EnvError, EnvMissingError } from './errors.js';
import { defaultReporter } from './reporter.js';
/**
* Validate a single env var, given a spec object
*
* @throws EnvError - If validation is unsuccessful
* @return - The cleaned value
*/
function validateVar({ spec, name, rawValue, }) {
if (typeof spec._parse !== 'function') {
throw new EnvError(`Invalid spec for "${name}"`);
}
const value = spec._parse(rawValue);
if (spec.choices) {
if (!Array.isArray(spec.choices)) {
throw new TypeError(`"choices" must be an array (in spec for "${name}")`);
}
else if (!spec.choices.includes(value)) {
throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`);
}
}
if (value == null)
throw new EnvError(`Invalid value for env var "${name}"`);
return value;
}
// Format a string error message for when a required env var is missing
export function formatSpecDescription(spec) {
const egText = spec.example ? ` (eg. "${spec.example}")` : '';
const docsText = spec.docs ? `. See ${spec.docs}` : '';
return `${spec.desc}${egText}${docsText}`;
}
const readRawEnvValue = (env, k) => {
const result = env[k];
if (typeof result == 'string' && !result.trim()) {
return undefined;
}
return result;
};
/**
* Perform the central validation/sanitization logic on the full environment object
*/
export function getSanitizedEnv(environment, specs, options = {}) {
const cleanedEnv = {};
const castedSpecs = specs;
const errors = {};
const varKeys = Object.keys(castedSpecs);
const rawNodeEnv = readRawEnvValue(environment, 'NODE_ENV');
for (const k of varKeys) {
const spec = castedSpecs[k];
const rawValue = readRawEnvValue(environment, k);
try {
// If no value was given and default/devDefault/testDefault were provided, return the
// appropriate default value without passing it through validation
if (rawValue === undefined) {
// Use testDefault only when NODE_ENV is 'test'. Takes priority over devDefault and default.
if (rawNodeEnv === 'test' && Object.hasOwn(spec, 'testDefault')) {
cleanedEnv[k] = spec.testDefault;
continue;
}
// Use devDefault values only if NODE_ENV was explicitly set, and isn't 'production'
const usingDevDefault = rawNodeEnv && rawNodeEnv !== 'production' && Object.hasOwn(spec, 'devDefault');
if (usingDevDefault) {
cleanedEnv[k] = spec.devDefault;
continue;
}
if ('default' in spec) {
cleanedEnv[k] = spec.default;
continue;
}
// Throw error when no default value is provided
cleanedEnv[k] = undefined;
throw new EnvMissingError(formatSpecDescription(spec));
}
cleanedEnv[k] = validateVar({ name: k, spec, rawValue });
}
catch (err) {
if (options?.reporter === null)
throw err;
if (err instanceof Error)
errors[k] = err;
}
}
// This block is for supporting requiredWhen. If that field was provided for a var's spec and
// its condition evaluates to a truthy value, ensure that env var is present.
for (const k of varKeys) {
if (errors[k] == undefined) {
const spec = castedSpecs[k];
if (cleanedEnv[k] == undefined &&
spec.requiredWhen !== undefined &&
spec.requiredWhen(cleanedEnv)) {
errors[k] = new EnvMissingError(formatSpecDescription(spec));
}
}
}
const reporter = options?.reporter || defaultReporter;
reporter({ errors, env: cleanedEnv });
return cleanedEnv;
}
//# sourceMappingURL=core.js.map