@typedotenv/core
Version:
typedotenv core library (dotenv utility for TypeScript)
64 lines (61 loc) • 2.15 kB
JavaScript
// src/index.ts
import { parse } from "dotenv";
// src/validation.ts
var ValidationError = class extends Error {
};
var validation = (parsed, { allowList, denyList, required, patterns }) => {
if (allowList) {
const notAllowed = Object.keys(parsed).filter(
(key) => !allowList.includes(key)
);
if (notAllowed.length > 0)
throw new ValidationError(
`Not allowed key found: ${notAllowed.join(", ")}`
);
}
if (denyList) {
const denied = denyList.filter((key) => typeof parsed[key] === "string");
if (denied.length > 0)
throw new ValidationError(`Denied key found: ${denied.join(", ")}`);
}
if (required) {
const notIncluded = required.filter(
(key) => typeof parsed[key] === "undefined"
);
if (notIncluded.length > 0)
throw new ValidationError(
`Required keys are not included: ${notIncluded.join(", ")}`
);
}
if (patterns) {
const notMatched = Object.entries(patterns).filter(([key, pattern]) => {
const value = parsed[key];
if (typeof value === "undefined")
return false;
return !value.match(new RegExp(pattern));
}).map(([k]) => k);
if (notMatched.length > 0)
throw new ValidationError(`Not allowed pattern found: ${notMatched}`);
}
};
// src/index.ts
var defaultPrefix = "/* Auto generated by typedotenv */";
var generate = (dotenv, options = {}) => {
const parsed = parse(dotenv);
validation(parsed, options);
const eol = options.eol ?? "\n";
const envObject = options.envObject ?? "process.env";
const typeAssertion = options.enableTypeAssertion ? " as string" : "";
const definitions = Object.keys(parsed).map((key) => {
const envVar = options.accessFromIndexSignature ? `${envObject}["${key}"]` : `${envObject}.${key}`;
return [
!options.disableRuntimeTypeCheck && `if (typeof ${envVar} !== 'string') throw new Error('${key} is not defined in .env');`,
`export const ${key} = ${envVar}${typeAssertion};`
].filter(Boolean).join(eol);
});
const code = [options.prefix ?? defaultPrefix, ...definitions].join(eol);
return code + eol;
};
export {
generate
};