UNPKG

@typedotenv/core

Version:

typedotenv core library (dotenv utility for TypeScript)

64 lines (60 loc) 2.46 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/index.ts var _dotenv = require('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 = _dotenv.parse.call(void 0, dotenv); validation(parsed, options); const eol = _nullishCoalesce(options.eol, () => ( "\n")); const envObject = _nullishCoalesce(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 = [_nullishCoalesce(options.prefix, () => ( defaultPrefix)), ...definitions].join(eol); return code + eol; }; exports.generate = generate; exports.default = module.exports;