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

    Building your own host + plugins

    • Host resolves dotenv context once per invocation: await program.resolveAndLoad(...).
    • Resolved context is available via cli.getCtx() inside any plugin mount/action.
    • Root hooks persist a merged “root options bag”: readMergedOptions(thisCommand).
    • The first parseAsync() installs the plugins and builds the qualified-name table (call brand() first on a direct host). It throws on a qualified-name collision or a plain long option that starts with <alias>-, and registers each command's hidden terminator (terminatorName(alias, path)). See the Qualified Names authoring guide.
    • Every parseAsync(argv?, { from }) normalizes argv first (normalizeArgv, exported from cliHost): each qualified option (--vc-aws-profile p) moves to its owner as --profile=p, typed terminators are dropped, and a default subcommand entered at a token is written in (vc node -h → vc cmd node -h). Normalization errors go through this.error() (exit 1). -h left with the root renders top-level help. The root's rawArgs is the normalized user arguments. Sync parse() throws. See the Qualified options guide.
    • Help (every command, plain new Command() mounts included): own option lines end with (anywhere: --<qualified name>) (not --help); each subcommand lists its ancestors' visible options by qualified name in <owner> options (anywhere) sections; root help lists -h, -V and every untagged root option; hidden options (hideHelp(), rootOptionVisibility from createCli and config, terminators) appear nowhere.
    • Terminators are written wherever the next written token would be taken as a value: after a bare optional option, and before a default subcommand written in after an open variadic or optional value (vc -c npm test --watch → vc -c npm test --vc-q1r1s cmd --watch).
    • Nested CLI aliases: pick one that doesn't start with another CLI's alias followed by a dash (vc-test under vc fails: vc claims every --vc-* token). There is no separate check.
    • Known limitation: a plugin's new Command() parent without positional options keeps parsing its options after its subcommand, so if it declares the child's plain flag it takes the child's qualified option. Don't reuse the flag, or call .enablePositionalOptions() on the parent.
    • @karmaniverous/get-dotenv is an optional peerDependency ^8 (peerDependenciesMeta: { optional: true }) plus a devDependency, never a dependency.
    • The main entry (.) never imports get-dotenv, not even import type. The plugin and its config schema live in a ./get-dotenv subpath. Logger/ProcessEnv types the main entry exposes are defined locally.
    • Import z from zod (cliHost no longer re-exports it) and declare zod as a dependency, kept external.
    • A bin is a launcher that loads the CLI module with a dynamic import(); on ERR_MODULE_NOT_FOUND for get-dotenv it prints the local/global/npx install routes and exits 1.
    • createCli({ importMetaUrl: import.meta.url }) is required.
    • See the Packaging authoring guide and the Migrating to 8.0 guide.
    import { definePlugin } from '@karmaniverous/get-dotenv/cliHost';

    export const helloPlugin = () =>
    definePlugin({
    ns: 'hello',
    setup(cli) {
    cli.description('Say hello').action(() => {
    const ctx = cli.getCtx();
    console.log('dotenv keys:', Object.keys(ctx.dotenv).length);
    });
    },
    });

    Use groupPlugins to group child plugins under a shared prefix (e.g. smoz getdotenv init).

    import { groupPlugins } from '@karmaniverous/get-dotenv/cliHost';
    import { initPlugin } from '@karmaniverous/get-dotenv/plugins';

    program.use(groupPlugins({ ns: 'getdotenv' }).use(initPlugin()));

    Prefer the plugin-bound helper createPluginDynamicOption to render help text that reflects the resolved configuration for that specific plugin instance.

    import { z } from 'zod';
    import { definePlugin } from '@karmaniverous/get-dotenv/cliHost';

    const helloConfigSchema = z.object({
    loud: z.boolean().optional().default(false),
    });

    export const helloPlugin = () => {
    const plugin = definePlugin({
    ns: 'hello',
    configSchema: helloConfigSchema,
    setup(cli) {
    cli
    .description('Say hello')
    .addOption(
    // Helper infers config type
    plugin.createPluginDynamicOption(
    cli,
    '--loud',
    (
    _bag,
    pluginCfg, // inferred as Readonly<HelloConfig>
    ) =>
    `print greeting in ALL CAPS${pluginCfg.loud ? ' (default)' : ''}`,
    ),
    )
    .action(() => {
    const pluginCfg = plugin.readConfig(cli);
    // use pluginCfg.loud
    });
    },
    });
    return plugin;
    };

    To reflect defaults in subcommand help without creating separate plugins:

    1. Model defaults in your plugin schema (nested object).
    2. Pass the subcommand instance to createPluginDynamicOption.
    const sub = cli.command('sub');
    sub.addOption(
    plugin.createPluginDynamicOption(
    sub, // target the subcommand
    '--mode <val>',
    (_bag, pluginCfg) => `mode (default: ${pluginCfg.sub.mode})`,
    ),
    );

    For plugins with multiple subcommands (e.g. aws dynamodb create), follow the Resolver Pattern.

    1. Schema: Model defaults as nested objects in the plugin schema (e.g. create: { version: ... }).
    2. Registration: action handler simply calls a resolver, then a service. Keep it thin.
    3. Resolver: Pure function (flags, config, envRef) => ServiceInput.
      • Handles precedence: Flags > Config > Defaults.
      • Handles expansion (see below).
    • Config Strings: The host interpolates these before your plugin runs. Do not re-expand pluginCfg values.
    • Flag Values: You must expand these manually if you want ${VAR} support. Use dotenvExpand(val, { ...process.env, ...ctx.dotenv }).
    • Wiring Tests: Use cli.install() to verify commands/options exist (smoke test).
    • Resolver Tests: Unit test the resolver function for precedence and logic.

    Always build a normalized child env:

    import { buildSpawnEnv } from '@karmaniverous/get-dotenv';
    const env = buildSpawnEnv(process.env, ctx.dotenv);

    Honor capture contract:

    import {
    readMergedOptions,
    runCommand,
    shouldCapture,
    } from '@karmaniverous/get-dotenv/cliHost';

    const bag = readMergedOptions(thisCommand);
    const capture = shouldCapture(bag.capture);

    await runCommand('echo OK', bag.shell ?? false, {
    env,
    stdio: capture ? 'pipe' : 'inherit',
    });

    Expand at action time using the resolved context:

    import { dotenvExpand } from '@karmaniverous/get-dotenv';

    const raw = String(opts.tableName ?? '');
    const envRef = { ...process.env, ...cli.getCtx().dotenv };
    const expanded = dotenvExpand(raw, envRef) ?? raw;

    Use these in your plugin setup to validate numeric flags at parse time.

    import {
    parseFiniteNumber,
    parsePositiveInt,
    parseNonNegativeInt,
    } from '@karmaniverous/get-dotenv';

    cli.option('--limit <n>', 'max items', parsePositiveInt('limit'));

    Use this helper to protect destructive actions.

    import { ensureForce } from '@karmaniverous/get-dotenv/cliHost';

    cli.action((args, opts) => {
    if (!ensureForce(opts.force, 'delete table')) return;
    // proceed...
    });

    Validate that an object satisfies the AWS-compatible logger contract (debug|info|warn|error). Throws if invalid.

    import { assertLogger } from '@karmaniverous/get-dotenv';
    const logger = assertLogger(maybeLogger);
    • traceChildEnv({ parentEnv, dotenv, keys?, redact?, ... })
    • redactDisplay(key, value, ...)
    • maybeWarnEntropy(key, value, origin, opts, write)

    These are presentation-only helpers to mirror the shipped CLI behavior.