@karmaniverous/get-dotenv
    Preparing search index...

    Config files and overlays (always-on)

    The config loader lets you specify environment values using JSON/YAML or JS/TS config files, then overlay them deterministically with privacy and source precedence.

    Behavior: In the shipped CLI (plugin-first host) and the generator path, the loader/overlay pipeline is always active and is a no-op when no config files are present.

    When enabled, the loader discovers up to three configs in the following order:

    1. Packaged root: the host CLI's package root, “public” only. That is the nearest package.json above the importMetaUrl the host passes to createCli (for the shipped getdotenv CLI, get-dotenv's own package). Skipped when it is the project root.
      • getdotenv.config.json
      • getdotenv.config.yaml / .yml
      • getdotenv.config.js / .mjs / .cjs
      • getdotenv.config.ts / .mts / .cts
    2. Project root (your repository)
      • Public:
        • getdotenv.config.json
        • getdotenv.config.yaml / .yml
        • getdotenv.config.js / .mjs / .cjs
        • getdotenv.config.ts / .mts / .cts
      • Local (private, gitignored conventionally):
        • getdotenv.config.local.json
        • getdotenv.config.local.yaml / .yml
        • getdotenv.config.local.js / .mjs / .cjs
        • getdotenv.config.local.ts / .mts / .cts

    Notes:

    • Packaged .local is not expected by policy and is ignored.
    • A host's packaged config replaces get-dotenv's own; there is never a third layer. A host whose package is also the project (a CLI that lives in the repo it runs in) gets no packaged layer, so its config applies once, as project config. See Host identity.
    • The first matching “public” file per scope is used; the same for “local”.

    JSON/YAML (data only, always-on; no-op when no files are present):

    • Allowed keys:
      • rootOptionDefaults?: Partial — collapsed, CLI‑like flags and strings. Supported keys:
        • Targeting: env, defaultEnv, defaultEnvKey, paths, pathsDelimiter, pathsDelimiterPattern, dotenvToken, privateToken.
        • Output/Vars: vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, outputPath. A vars string is split into pairs at the delimiter and each pair at its first assignor, so A=1 B=x=y sets B to x=y.
        • Loading: loadProcess, dynamicPath.
        • Exclusions: excludeAll, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic.
        • Execution: shell, capture.
        • Diagnostics: log, debug, trace, strict.
        • Redaction: redact, redactPatterns.
        • Entropy: warnEntropy, entropyThreshold, entropyMinLength, entropyWhitelist.
        • Rejected in every format (the config is invalid): dynamic (use the top-level dynamic of a JS/TS config) and logger.
      • rootOptionVisibility?: Partial<Record<keyof RootOptionsShape, boolean>> — help‑time visibility (false hides a flag; true shows it again, undoing a lower layer’s false).
      • scripts?: Record<string, string | { cmd: string; shell?: string | boolean }>
      • vars?: Record<string, string> (global, public)
      • envVars?: Record<string, Record<string, string>> (per‑env, public)
      • plugins?: Record<string, unknown>
      • requiredKeys?: string[]
    • Disallowed in JSON/YAML (this step): dynamic and schema — use JS/TS instead.

    JS/TS (data + dynamic):

    • Accepts all JSON/YAML keys and also:
      • dynamic?: GetDotenvDynamic — a map where values are either strings or functions of the form (vars: Record<string, string | undefined>, env?: string) => string | undefined.
      • schema?: unknown — a schema object (e.g., a Zod schema) whose safeParse(finalEnv) will be executed once after overlays.

    TS support:

    • Direct import works if a TS loader is present.
    • Otherwise, the loader auto-bundles via esbuild when available; if esbuild is not present, it falls back to a simple TypeScript transpile for single-file modules without imports.
    • The esbuild compile leaves Node built-ins and installed ES module packages to Node: an import of a package name that resolves to an ES module of that package (linked and workspace packages included) stays an import, resolved from the config file's directory, so a config shares the package instances the rest of the project uses. exports and main resolve as Node resolves them. Everything else is bundled as before: relative imports (also in a config shipped inside node_modules), tsconfig path aliases, TypeScript and JSON files, CommonJS packages (which may require() Node built-ins) and require() calls. A require() that can only be resolved at run time (a computed name, an optional dependency) resolves from the config file's directory. A package installed under an npm alias ("zod3": "npm:zod@^3") is bundled too, so the config gets its own copy of it.
    • When a config fails to load, the CLI prints each underlying cause beneath the error, including what esbuild and the TypeScript fallback each reported. Add --debug (or set GETDOTENV_DEBUG=1) for the full stack traces.
    • Operational root flags must live under rootOptionDefaults. Do not place root toggles (e.g., env, shell, loadProcess, log, exclude*, trace, strict, redact family, entropy family, splitters) at the top level in JSON/YAML. Put them under rootOptionDefaults to control both help‑time labels and runtime defaults. In a TS config, the defineGetDotenvConfig() type has exactly the loader's keys, so a top-level root option is a type error.
    • scripts belongs at the top level only. Do not nest scripts inside rootOptionDefaults.
    • dynamic and schema are JS/TS‑only. JSON/YAML loader rejects them.

    Root options resolve from one stack, higher wins: CLI flags, then the parent options bag (process.env.getDotenvCliOptions, in a nested run), then config rootOptionDefaults (project local, project public, packaged), then createCli({ rootOptionDefaults }), then the built-in defaults. createCli defaults are not Commander option defaults, so config and the parent bag override them.

    Each ON/OFF family (-p/-P loadProcess, -l/-L log, --debug/--debug-off, --redact/--redact-off, --entropy-warn/--entropy-warn-off warnEntropy, and the five exclusions -z/-Z, -n/-N, -g/-G, -r/-R, -u/-U) resolves the same way:

    • an explicit ON flag turns it on;
    • an explicit OFF flag turns it off, even when rootOptionDefaults (or a built-in default, such as loadProcess: true and warnEntropy: true) turns it on;
    • with neither flag, the value comes from the defaults.

    For the exclusions, an individual flag (-r, -R, …) beats -a/--exclude-all and -A/--exclude-all-off, which beat the defaults. In the defaults, rootOptionDefaults.excludeAll: true (in config or createCli) turns on all five exclusions, and an individual default such as excludePrivate: false beats it.

    Config privacy derives from the filename suffix:

    • Public: getdotenv.config.json / .yaml / .yml (shared in VCS).
    • Local: getdotenv.config.local.json / .yaml / .yml (gitignored).

    The loader overlays config-provided values onto the “base” file-derived dotenv values using these axes (higher wins):

    1. Kind: dynamic > env > global
    2. Privacy: local > public
    3. Source: project > packaged > base

    The overlay flow:

    1. Base: resolve file cascade using getDotenv (exclude dynamic; ignore programmatic vars).
    2. Overlay config sources in order: packaged (public only) → project public → project local.
    3. Apply dynamic in order, a later map winning on a shared key: config dynamic from JS/TS (packaged → project public → project local) → programmatic dynamic (if provided) → file dynamicPath (highest dynamic tier).
    4. Optional effects: outputPath (write consolidated dotenv; values quoted so dotenv reads them back exactly), log (print final map), loadProcess (copy into process.env: a string sets the key; an unset value, or a key deleted by a dynamic null, deletes it).

    When no explicit -e flag is provided, get-dotenv resolves the target environment in three tiers:

    1. Explicit -e flag — highest priority, used as-is.
    2. defaultEnvKey lookup — a global-only pre-pass loads dotenv files (excluding env-scoped files) and looks up the variable named by defaultEnvKey (default: DEFAULT_ENV). If found, its value becomes the resolved environment.
    3. Static defaultEnv — the fallback from config if neither of the above produces a value.

    Example: if .env.local contains DEFAULT_ENV=bali and your config sets defaultEnv: 'dev', the resolved environment is bali (tier 2 wins over tier 3).

    By the time plugins run, bag.env is always the fully resolved environment — plugins never need to handle defaulting themselves.

    There are three distinct expansion stages:

    • Root option parse-time expansion (CLI only): selected root option values (for example --env, --output-path, --dotenv-token, --private-token, --dynamic-path, --paths) are dotenv-expanded once against process.env via an option parser; they do not see { ...ctx.dotenv }. --vars is not one of them: its values are expanded once, in the vars layer, so -v 'P=\$5' sets P to $5.
    • Dotenv/config composition expansion (host): dotenv values from files, config vars/envVars and explicit vars (--vars, programmatic vars) are expanded progressively during composition, each against process.env overlaid with the values composed so far (composed values win); later keys can reference earlier ones. A referenced value is substituted verbatim, as composed, and never expanded again: with .env P=\$5, config vars: { Q: '$P' } gives Q=$5. While a key is being expanded, a reference to it sees the value composed before it, else counts as unset.
    • Per-plugin interpolation: before validation and afterResolve, the host deep-interpolates each plugin’s config slice (string leaves only) once against { ...ctx.dotenv, ...process.env } (process.env wins).

    Notes:

    • getDotenv() (programmatic API) expands outputPath against the composed variables (it can reference other dotenv keys). In the CLI, argv-provided values (like --output-path) are expanded against process.env at parse time, but values coming from rootOptionDefaults are not automatically expanded.

    You can validate the final composed environment via config:

    • JSON/YAML: requiredKeys?: string[] — each key must be present (value !== undefined) in the final env.
    • JS/TS: schema?: { safeParse(finalEnv) } (e.g., a Zod schema).

    Behavior:

    • Validation runs once against the composed env (host/generator paths), after overlays and dynamic variables are applied.
    • By default, issues are logged at error level and the run continues. Set --strict (or strict: true in options) to fail with a non‑zero exit when issues are detected.

    Examples:

    # getdotenv.config.yaml
    requiredKeys:
    - APP_SETTING
    - ENV_SETTING
    // getdotenv.config.ts
    import { z } from 'zod';
    export default {
    schema: z.object({
    APP_SETTING: z.string().min(1),
    ENV_SETTING: z.string().optional(),
    }),
    };

    defineGetDotenvConfig has two overloads:

    • Schema-driven (preferred): when cfg.schema is a Zod object schema, the Vars bag seen by dynamic functions is inferred from the schema's input type (z.input<typeof schema>) — no Vars type parameter needed. The schema's input must be string-valued (ProcessEnv-compatible: every property string | undefined); a schema that coerces from a non-string input (for example, a bare z.coerce.number() leaf, whose input is unknown) is a type error. Use z.coerce.number<string>() to validate a numeric value with string input.
    • Legacy: defineGetDotenvConfig<Vars, Env>(), an explicit Vars type parameter (with or without a schema, including a non-Zod validator that merely exposes safeParse), keeps compiling unchanged.
    // getdotenv.config.ts
    import { z } from 'zod';
    import { defineGetDotenvConfig } from '@karmaniverous/get-dotenv';

    export default defineGetDotenvConfig({
    schema: z.object({
    APP_SETTING: z.string(),
    ENV_SETTING: z.string().optional(),
    }),
    dynamic: {
    // `vars` is typed from `schema` above: { APP_SETTING: string; ENV_SETTING?: string }
    GREETING: (vars) => `Hello ${vars.APP_SETTING}`,
    },
    });

    Exported from the package root. Composes a new typed config from a base and an optional overrides slice; neither argument is mutated. Useful for a shared base config (for example, exported by an internal package for every service in an org) extended per-project.

    // shared-base/getdotenv.config.ts
    import { z } from 'zod';
    import { defineGetDotenvConfig } from '@karmaniverous/get-dotenv';

    export const baseConfig = defineGetDotenvConfig({
    schema: z.object({ SERVICE_NAME: z.string() }),
    vars: { SERVICE_NAME: 'unnamed' },
    dynamic: {
    GREETING: (vars) => `Hello from ${vars.SERVICE_NAME}`,
    },
    });
    // getdotenv.config.ts
    import { z } from 'zod';
    import { extendGetDotenvConfig } from '@karmaniverous/get-dotenv';

    import { baseConfig } from 'shared-base/getdotenv.config';

    export default extendGetDotenvConfig(baseConfig, {
    schema: z.object({ REGION: z.string() }),
    requiredKeys: ['REGION'],
    dynamic: {
    // Sees both SERVICE_NAME (base) and REGION (this override), with no
    // `Vars` annotation: `Vars` is the merged schema's input.
    TAG: (vars) => `${vars.SERVICE_NAME}-${vars.REGION}`,
    },
    });

    Merge semantics, by key:

    Key Merge
    schema The base Zod object schema extended with the override's fields; the override wins on a clashing key (z.input<Merged> has the override's type for that field). Requires Zod object schemas (z.object(...)) when both sides declare a schema — the call throws at runtime otherwise. Either side alone (or neither) passes through unchanged.
    dynamic Object spread: an overridden key keeps the base key's position, so values that depend on it are still computed after it (dynamic evaluation runs in key-insertion order); new keys come after all base keys.
    requiredKeys Union, base order first, de-duplicated.
    plugins, rootOptionDefaults, rootOptionVisibility, scripts, vars, envVars (plain objects) Deep merge, override wins (the same semantics as the library's internal defaultsDeep).
    Other arrays and scalars Override replaces (for example, rootOptionDefaults.redactPatterns is replaced wholesale, not concatenated).

    extendGetDotenvConfig(base) with no overrides returns a new, structurally equivalent config.

    validateEnvAgainstSources now validates the final composed env against the schema of every config layer that has one (packaged, project public, project local) instead of stopping at the first one found, and requiredKeys are unioned across the layers that use them. A config set that uses a single layer is unaffected. Previously, a project schema silently shadowed a packaged layer's schema; if your packaged layer's schema relied on that shadowing, review it before upgrading.

    Plugin configuration is discovered under plugins.<mount-path> in the same packaged/project public/local files. The mount path is the chain of effective namespaces from the root (a .use(plugin, { ns }) override replaces the plugin's own ns), e.g. aws/whoami or deploy-api. The host merges slices by precedence (packaged → project/public → project/local) and deep‑interpolates string leaves once against { ...ctx.dotenv, ...process.env } (process.env wins for plugin slices). Plugins read their own validated slice via the instance‑bound helper plugin.readConfig(cli).

    Location and shape:

    {
    "plugins": {
    "batch": {
    "rootPath": "./packages"
    },
    "aws/dynamodb": {
    "create": { "version": "v1" }
    },
    "my-plugin": {
    "scripts": {
    "build": { "cmd": "npm run build", "shell": "/bin/bash" }
    },
    "shell": false
    }
    }
    }

    Precedence and timing:

    • Source/Privacy: project/local > project/public > packaged.
    • Strings are interpolated once just before validation/afterResolve; later consumers (e.g., dynamic help callbacks) receive the already‑interpolated value. Prefer the plugin‑bound helper createPluginDynamicOption(cli, ...) to surface effective defaults in help text without by‑id lookups.

    For compile‑time DX, overlayEnv preserves the key set:

    • Without programmaticVars, the result is typed as your base B.
    • With programmaticVars, the result is typed as B & P.
    import { overlayEnv } from '@karmaniverous/get-dotenv/env/overlay';

    const base = { A: 'a' };
    const out = overlayEnv({
    base,
    env: 'dev',
    configs: {},
    programmaticVars: { B: 'b' },
    });
    // out is typed as { A?: string } & { B?: string } at compile time

    Presentation‑only diagnostics help audit values without altering runtime behavior:

    • Redaction (--redact): masks secret‑like keys in -l/--log and --trace outputs. The built-in patterns match secret, token, pass/password, api_key/api-key/apikey and key, case-insensitively, as a whole word or as an underscore- or dash-delimited segment of the key: API_SECRET, DB_PASSWORD and GITHUB_TOKEN are masked; SECRETARY and MONKEY are not. Custom patterns (--redact-pattern <pattern...>, rootOptionDefaults.redactPatterns, or redactPatterns in getDotenv options) add to the built-in patterns. A RegExp pattern is used without its g and y flags, so it matches every key.
    • Entropy warnings (on by default):
      • Once‑per‑key messages when printable strings of at least --entropy-min-length characters (default 16) exceed --entropy-threshold bits/char (default 3.8). Both flags take numbers (a non-number is a usage error), and their help labels show the effective defaults.
      • Surfaces: --trace and -l/--log, on the CLI and in getDotenv({ log: true }).
      • Whitelisted keys are never checked. The built-in whitelist (^GIT_, ^npm_, ^CI$, SHLVL) always applies: patterns from --entropy-whitelist, rootOptionDefaults.entropyWhitelist or entropyWhitelist in getDotenv options add to it.

    You can define a scripts table in config. Script strings are resolved by the cmd and batch commands. Only the table's own keys are script names: a command named after an inherited object property (toString, constructor) runs as typed. If you want a named script to inherit the root shell behavior, use the string form; the object form { cmd, shell } uses shell as the effective shell for that entry (and when omitted, the script currently runs with shell-off rather than inheriting the root shell):

    {
    "scripts": {
    "bash-only": { "cmd": "echo $SHELL && echo OK", "shell": "/bin/bash" },
    "plain": { "cmd": "node -v", "shell": false }
    }
    }

    Then:

    getdotenv cmd bash-only
    getdotenv cmd plain

    One script is built in: git-status runs git status -s -u -b (the ## <branch> line, then short status with untracked files) with shell: true, the OS default shell (PowerShell on Windows, /bin/bash elsewhere). Its command uses no shell operators, so it works under PowerShell 5.1, which has no &&. When you write a script for that default shell on Windows, do the same. Config scripts are merged with it.

    For help‑time visibility of root flags (e.g., hiding --capture or an entire family like --shell/--shell-off), set rootOptionVisibility in JSON/YAML/JS/TS config. Precedence matches root defaults: createCli < packaged/public < project/public < project/local; a higher layer’s true shows a flag a lower layer hid. Every root flag has a key, including env, outputPath, defaultEnvKey, debug and excludeAll. The merged visibility applies to every help rendering: a hidden flag leaves root help and the inherited <alias> options (anywhere) section of every subcommand's help, qualified name included (see Qualified options).