UNPKG

@hairy/lnv

Version:

Loading environment variables in Next.js and other frameworks can be quite cumbersome, and using dotenv or vault at runtime is also inconvenient. That's why my created this tool

81 lines (78 loc) 2.49 kB
import {createRequire as __createRequire} from 'module';var require=__createRequire(import.meta.url); import { authEnvironment, executionScript, loadEnvironment, mergeParseEnvironment, parseUserConfig, readEnvironment } from "./chunk-M3SZUPO5.js"; import { context } from "./chunk-DYEG65P7.js"; import { run } from "./chunk-NC5LCYHV.js"; import { write, writeDts } from "./chunk-MPPGICUB.js"; // src/lnv.ts import process from "node:process"; async function lnv(options) { Object.assign(context, options); await parseUserConfig(); context.entries.push("env"); context.entries.unshift("local"); await readEnvironment(); await authEnvironment(); await loadEnvironment(); await executionScript(); Object.assign(context.parsed, context.before); Object.assign(context.parsed, context.env); Object.assign(context.parsed, context.after); mergeParseEnvironment(); if (context.dts) { const filepath = context.dts === true ? "process-env.d.ts" : context.dts; writeDts(filepath, context.parsed); } const message = assembleMessage(); if (context.run) { message && console.log(message); console.log(); await run(context.run, context.parsed); } if (context.write) { write(`${process.cwd()}/.env`, context.parsed); console.log(); message && console.log(message); } } function assembleMessage() { const notFoundParsed = !Object.keys(context.parsed).length; const notFoundManual = !Object.keys(context.env || {}).length; const notFoundFiles = !context.parsedFiles.length; if (notFoundParsed && notFoundFiles && notFoundManual) { console.log("No environment variables found"); return ""; } let message = ""; if (notFoundFiles && !notFoundManual) { message = context.run ? `Successfully loaded ${context.parsedFiles.join(",")} to runtime environment` : `Successfully loaded ${context.parsedFiles.join(",")} to .env`; } else if (!notFoundFiles) { message = context.run ? `Successfully loaded ${context.parsedFiles.join(",")} to runtime environment` : `Successfully wrote ${context.parsedFiles.join(",")} to .env`; } if (!notFoundFiles && !notFoundManual) message += " and with variables:"; else if (!notFoundManual) message = "Successfully manual loaded environment variables"; if (context.env) { for (const [key, value] of Object.entries(context.env)) typeof value !== "undefined" && (message += ` ${key}=${value}`); } return message; } export { lnv };