import { z, ZodObject } from 'zod'; import { OptionValues, Command, InferCommandArguments, Option, CommandUnknownOpts } from '@commander-js/extra-typings'; /** * Dotenv provenance model (descriptor-only). * * Requirements addressed: * - Host ctx carries a dotenv provenance mapping describing per-key origin and override history. * - Provenance is descriptor-only (no value payloads). * - Provenance is an ordered stack per key in ascending precedence; the last entry is effective. * - Explicit unsets are represented as `op: 'unset'` without requiring deletion of keys from the env map. */ /** * Provenance kind for an entry in {@link DotenvProvenance}. * * @public */ type DotenvProvenanceKind = 'file' | 'config' | 'vars' | 'dynamic'; /** * Operation represented by a provenance entry. * * @public */ type DotenvProvenanceOp = 'set' | 'unset'; /** * Base shape for all provenance entries. * * @public */ interface DotenvProvenanceEntryBase { /** * The kind of provenance entry. */ kind: DotenvProvenanceKind; /** * The operation applied at this layer. */ op: DotenvProvenanceOp; } /** * Provenance entry representing a value sourced from a dotenv file in the cascade. * * @public */ interface DotenvFileProvenanceEntry extends DotenvProvenanceEntryBase { /** Discriminator. */ kind: 'file'; /** Global vs env-scoped file. */ scope: 'global' | 'env'; /** Public vs private file. */ privacy: 'public' | 'private'; /** Environment name (required when scope is `env`). */ env?: string; /** * The corresponding `paths[]` entry as provided by the caller/CLI. * This is not an absolute path by policy. */ path: string; /** * The computed dotenv filename token (e.g., `.env`, `.env.dev`, `.env.local`, `.env.dev.local`). */ file: string; } /** * Provenance entry representing a value sourced from config overlays (`vars` / `envVars`). * * @public */ interface DotenvConfigProvenanceEntry extends DotenvProvenanceEntryBase { /** Discriminator. */ kind: 'config'; /** Global vs env-scoped config slice. */ scope: 'global' | 'env'; /** Public vs private on the privacy axis (`local` config maps to `private`). */ privacy: 'public' | 'private'; /** Environment name (required when scope is `env`). */ env?: string; /** Packaged vs project config origin. */ configScope: 'packaged' | 'project'; /** Public vs local config file. */ configPrivacy: 'public' | 'local'; } /** * Provenance entry representing explicit variables overrides. * * Notes: * - This kind represents values injected via `vars` (CLI/programmatic), not dotenv files. * * @public */ interface DotenvVarsProvenanceEntry extends DotenvProvenanceEntryBase { /** Discriminator. */ kind: 'vars'; } /** * Source tier for dynamic variables. * * @public */ type DotenvDynamicSource = 'config' | 'programmatic' | 'dynamicPath'; /** * Provenance entry representing dynamic variables. * * @public */ interface DotenvDynamicProvenanceEntry extends DotenvProvenanceEntryBase { /** Discriminator. */ kind: 'dynamic'; /** Dynamic source tier. */ dynamicSource: DotenvDynamicSource; /** * The `dynamicPath` value as provided by the caller/CLI when `dynamicSource` is `dynamicPath`. * This is not resolved to an absolute path by provenance policy. */ dynamicPath?: string; } /** * Union of all supported provenance entry shapes. * * @public */ type DotenvProvenanceEntry = DotenvFileProvenanceEntry | DotenvConfigProvenanceEntry | DotenvVarsProvenanceEntry | DotenvDynamicProvenanceEntry; /** * Per-key provenance history. * * Each key maps to an array of entries ordered in ascending precedence (lower to higher). * * @public */ type DotenvProvenance = Record; /** * Resolved CLI options schema. * For the current step this mirrors the RAW schema; later stages may further * narrow types post-resolution in the host pipeline. */ /** * CLI options schema (resolved). * * Today this mirrors {@link getDotenvCliOptionsSchemaRaw}, but is kept as a distinct export * so future resolution steps can narrow or materialize defaults without breaking the API. * * @public */ declare const getDotenvCliOptionsSchemaResolved: z.ZodObject<{ defaultEnv: z.ZodOptional; defaultEnvKey: z.ZodOptional; dotenvToken: z.ZodOptional; dynamicPath: z.ZodOptional; dynamic: z.ZodOptional>; env: z.ZodOptional; excludeDynamic: z.ZodOptional; excludeEnv: z.ZodOptional; excludeGlobal: z.ZodOptional; excludePrivate: z.ZodOptional; excludePublic: z.ZodOptional; loadProcess: z.ZodOptional; log: z.ZodOptional; logger: z.ZodDefault; outputPath: z.ZodOptional; privateToken: z.ZodOptional; debug: z.ZodOptional; strict: z.ZodOptional; capture: z.ZodOptional; trace: z.ZodOptional]>>; redact: z.ZodOptional; warnEntropy: z.ZodOptional; entropyThreshold: z.ZodOptional; entropyMinLength: z.ZodOptional; entropyWhitelist: z.ZodOptional>; redactPatterns: z.ZodOptional>; paths: z.ZodOptional; pathsDelimiter: z.ZodOptional; pathsDelimiterPattern: z.ZodOptional; scripts: z.ZodOptional>; shell: z.ZodOptional>; vars: z.ZodOptional; varsAssignor: z.ZodOptional; varsAssignorPattern: z.ZodOptional; varsDelimiter: z.ZodOptional; varsDelimiterPattern: z.ZodOptional; }, z.core.$strip>; /** * Resolved programmatic options schema (post-inheritance). * For now, this mirrors the RAW schema; future stages may materialize defaults * and narrow shapes as resolution is wired into the host. */ /** * Programmatic options schema (resolved). * * Today this mirrors {@link getDotenvOptionsSchemaRaw}, but is kept as a distinct export * so future resolution steps can narrow or materialize defaults without breaking the API. * * @public */ declare const getDotenvOptionsSchemaResolved: z.ZodObject<{ defaultEnv: z.ZodOptional; defaultEnvKey: z.ZodOptional; dotenvToken: z.ZodOptional; dynamicPath: z.ZodOptional; dynamic: z.ZodOptional>; env: z.ZodOptional; excludeDynamic: z.ZodOptional; excludeEnv: z.ZodOptional; excludeGlobal: z.ZodOptional; excludePrivate: z.ZodOptional; excludePublic: z.ZodOptional; loadProcess: z.ZodOptional; log: z.ZodOptional; logger: z.ZodDefault; outputPath: z.ZodOptional; paths: z.ZodOptional>; privateToken: z.ZodOptional; vars: z.ZodOptional>>; }, z.core.$strip>; /** * Minimal root options shape shared by CLI and generator layers. * Keep keys optional to respect exactOptionalPropertyTypes semantics. * * @public */ interface RootOptionsShape { /** Target environment (dotenv-expanded). */ env?: string; /** Explicit variable overrides (dotenv-expanded). */ vars?: string; /** Command to execute (dotenv-expanded). */ command?: string; /** Output path for the consolidated environment file (dotenv-expanded). */ outputPath?: string; /** * Shell execution strategy. * - `true`: use default OS shell. * - `false`: use plain execution (no shell). * - string: use specific shell path. */ shell?: string | boolean; /** Whether to load variables into `process.env`. */ loadProcess?: boolean; /** Exclude all variables from loading. */ excludeAll?: boolean; /** Exclude dynamic variables. */ excludeDynamic?: boolean; /** Exclude environment-specific variables. */ excludeEnv?: boolean; /** Exclude global variables. */ excludeGlobal?: boolean; /** Exclude private variables. */ excludePrivate?: boolean; /** Exclude public variables. */ excludePublic?: boolean; /** Enable console logging of loaded variables. */ log?: boolean; /** Enable debug logging to stderr. */ debug?: boolean; /** Capture child process stdio (useful for tests/CI). */ capture?: boolean; /** Fail on validation errors (schema/requiredKeys). */ strict?: boolean; /** Enable presentation-time redaction of secret-like keys. */ redact?: boolean; /** Enable entropy warnings for high-entropy values. */ warnEntropy?: boolean; /** Entropy threshold (bits/char) for warnings (default 3.8). */ entropyThreshold?: number; /** Minimum string length to check for entropy (default 16). */ entropyMinLength?: number; /** Regex patterns for keys to exclude from entropy checks. */ entropyWhitelist?: ReadonlyArray; /** Additional regex patterns for keys to redact. */ redactPatterns?: string[]; /** Default target environment when not specified. */ defaultEnv?: string; /** Env var name in global dotenv files that specifies the default environment. */ defaultEnvKey?: string; /** Token indicating a dotenv file (default: ".env"). */ dotenvToken?: string; /** Path to dynamic variables module (default: undefined). */ dynamicPath?: string; /** * Emit diagnostics for child env composition. * - `true`: trace all keys. * - `string[]`: trace selected keys. */ trace?: boolean | string[]; /** Paths to search for dotenv files (space-delimited string or array). */ paths?: string | string[]; /** Delimiter for paths string (default: space). */ pathsDelimiter?: string; /** Regex pattern for paths delimiter. */ pathsDelimiterPattern?: string; /** Token indicating private variables (default: "local"). */ privateToken?: string; /** Delimiter for vars string (default: space). */ varsDelimiter?: string; /** Regex pattern for vars delimiter. */ varsDelimiterPattern?: string; /** Assignment operator for vars (default: "="). */ varsAssignor?: string; /** Regex pattern for vars assignment operator. */ varsAssignorPattern?: string; /** Table of named scripts for execution. */ scripts?: ScriptsTable; } /** * Definition for a single script entry. */ interface ScriptDef { /** The command string to execute. */ cmd: string; /** Shell override for this script. */ shell?: TShell | undefined; } /** * Scripts table shape. */ type ScriptsTable = Record>; /** * Identity helper to define a scripts table while preserving a concrete TShell * type parameter in downstream inference. */ declare const defineScripts: () => >(t: T) => T; /** * Per-invocation context shared with plugins and actions. * * @public */ interface GetDotenvCliCtx { /** * Effective environment name after resolution (explicit -e \> defaultEnvKey \> defaultEnv). */ env?: string; /** * Fully resolved option bag used to compute this context. */ optionsResolved: TOptions; /** * Final composed dotenv environment for this invocation. */ dotenv: ProcessEnv; /** * Dotenv provenance history for {@link GetDotenvCliCtx.dotenv}. * * Descriptor-only: does not include value payloads. */ dotenvProvenance: DotenvProvenance; /** * Optional runtime plugin state bag. Plugins may publish non-sensitive metadata here. */ plugins?: Record; /** * Per-plugin validated configuration slices keyed by realized mount path. */ pluginConfigs?: Record; } /** * Options for branding the CLI. * * @public */ interface BrandOptions { /** CLI name. */ name?: string; /** CLI description. */ description?: string; /** CLI version string. */ version?: string; /** Import URL for resolving package version. */ importMetaUrl?: string; /** Custom help header text. */ helpHeader?: string; } /** * A minimal representation of an environment key/value mapping. * Values may be `undefined` to represent "unset". */ type ProcessEnv = Record; /** * Compatibility shape for root options allowing string inputs for vars/paths. * Used during CLI argument parsing before normalization. */ type RootOptionsShapeCompat = Omit & { /** * Extra variables as either a space‑delimited string of assignments * (e.g., `"FOO=1 BAR=2"`) or an object map of `string | undefined` values. */ vars?: string | ProcessEnv; /** * Dotenv search paths as a space‑delimited string or a pre‑split string[]. */ paths?: string | string[]; }; /** * Dynamic variable function signature. Receives the current expanded variables * and the selected environment (if any), and returns either a string to set * or `undefined` to unset/skip the variable. */ type GetDotenvDynamicFunction = (vars: ProcessEnv, env: string | undefined) => string | null | undefined; /** * A map of dynamic variable definitions. * Keys are variable names; values are either literal strings or functions. */ type GetDotenvDynamic = Record>; /** * Logger interface compatible with AWS SDK v3 expectations (`debug`, `info`, `warn`, `error`). * Consumers must provide an object that implements these four methods. * Additional methods (like `log`) are allowed but not required or used by this library. */ type Logger = Pick; /** * Validate that a candidate object satisfies the {@link Logger} contract. * Throws if the candidate is invalid. */ declare const assertLogger: (candidate: unknown) => Logger; /** * Canonical programmatic options type (schema-derived). * This type is the single source of truth for programmatic options. */ type GetDotenvOptions = Omit, 'logger' | 'dynamic'> & { /** * Compile-time overlay: narrowed logger for DX (schema stores unknown). */ logger: Logger; /** * Compile-time overlay: narrowed dynamic map for DX (schema stores unknown). */ dynamic?: GetDotenvDynamic; }; /** * Vars-aware dynamic helpers (compile-time DX). * DynamicFn: receive the current expanded variables and optional env. */ type DynamicFn = (vars: Vars, env?: string) => string | null | undefined; /** * Vars-aware dynamic map type used by {@link defineDynamic} and JS/TS configs. * * @typeParam Vars - The env var bag shape passed to dynamic functions. */ type DynamicMap = Record | ReturnType>>; /** * Helper to define a dynamic map with strong inference (Vars-aware). * * Overload A (preferred): bind Vars to your intended key set for improved inference. */ declare function defineDynamic>(d: T): T; /** * Overload B (backward-compatible): generic over legacy GetDotenvDynamic. * * Accepts legacy GetDotenvDynamic without Vars binding. */ declare function defineDynamic(d: T): T; /** * Typed config shape and builder for authoring JS/TS getdotenv config files. * * Compile-time only; the runtime loader remains schema-driven. */ interface GetDotenvConfig { /** * Operational root defaults applied by the host (collapsed families; stringly form). */ rootOptionDefaults?: Partial; /** Token indicating a dotenv file. */ dotenvToken?: string; /** Token indicating private variables. */ privateToken?: string; /** Paths to search for dotenv files. */ paths?: string | string[]; /** Whether to load variables into `process.env`. */ loadProcess?: boolean; /** Whether to log loaded variables. */ log?: boolean; /** Shell execution strategy. */ shell?: string | boolean; /** Scripts table. */ scripts?: ScriptsTable; /** Keys required to be present in the final environment. */ requiredKeys?: string[]; /** Validation schema (e.g. Zod). */ schema?: unknown; /** Global variables. */ vars?: Vars; /** Environment-specific variables. */ envVars?: Record>; /** Dynamic variable definitions. */ dynamic?: DynamicMap; /** Plugin configuration slices. */ plugins?: Record; } /** * Define a strongly‑typed get‑dotenv configuration document for JS/TS authoring. * * This helper is compile‑time only: it returns the input unchanged at runtime, * but enables rich TypeScript inference for `vars`, `envVars`, and `dynamic`, * and validates property names and value shapes as you author the config. * * @typeParam Vars - The string‑valued env map your project uses (for example, * `{ APP_SETTING?: string }`). Keys propagate to `dynamic` function arguments. * @typeParam Env - Allowed environment names used for `envVars` (defaults to `string`). * @typeParam T - The full config type being produced (defaults to `GetDotenvConfig`). * This type parameter is rarely supplied explicitly. * @param cfg - The configuration object literal. * @returns The same `cfg` value, with its type preserved for inference. */ declare function defineGetDotenvConfig = GetDotenvConfig>(cfg: T): T; /** * Internal helper type used by {@link InferGetDotenvVarsFromConfig}. * * This exists to give TypeDoc a stable symbol for the `vars` probe used in the * conditional type, avoiding anonymous `__type` warnings. * * @typeParam V - The `vars` bag shape declared on the config. */ interface GetDotenvConfigWithVars { /** * Variables declared on a typed getdotenv config document. */ vars?: V; } /** * Compile-time helper to derive the Vars shape from a typed getdotenv config document. */ type InferGetDotenvVarsFromConfig = T extends GetDotenvConfigWithVars ? V extends ProcessEnv ? V : never : never; /** * Converts programmatic CLI options to `getDotenv` options. * * Accepts "stringly" CLI inputs for vars/paths and normalizes them into * the programmatic shape. Preserves exactOptionalPropertyTypes semantics by * omitting keys when undefined. */ declare const getDotenvCliOptions2Options: ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, debug: _debug, scripts: _scripts, ...rest }: RootOptionsShapeCompat) => GetDotenvOptions; /** * Asynchronously process dotenv files of the form `.env[.][.]` * * @param options - `GetDotenvOptions` object * @returns The combined parsed dotenv object. * * @example Load from the project root with default tokens * ```ts * const vars = await getDotenv(); * console.log(vars.MY_SETTING); * ``` * * @example Load from multiple paths and a specific environment * ```ts * const vars = await getDotenv({ * env: 'dev', * dotenvToken: '.testenv', * privateToken: 'secret', * paths: ['./', './packages/app'], * }); * ``` * * @example Use dynamic variables * ```ts * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` } * const vars = await getDotenv({ dynamicPath: '.env.js' }); * ``` * * @remarks * - When {@link GetDotenvOptions | loadProcess} is true, the resulting variables are merged * into `process.env` as a side effect. * - When {@link GetDotenvOptions | outputPath} is provided, a consolidated dotenv file is written. * The path is resolved after expansion, so it may reference previously loaded vars. * * @throws Error when a dynamic module is present but cannot be imported. * @throws Error when an output path was requested but could not be resolved. */ declare function getDotenv(options?: Partial): Promise; declare function getDotenv(options: Partial & { vars: Vars; }): Promise; /** * Unify Scripts via the generic ScriptsTable so shell types propagate. */ type Scripts = ScriptsTable; /** * Canonical CLI options type derived from the Zod schema output. * Includes CLI-only flags (debug/strict/capture/trace/redaction/entropy), * stringly paths/vars, and inherited programmatic fields (minus normalized * shapes that are handled by resolution). */ type GetDotenvCliOptions = Omit, 'logger' | 'dynamic' | 'scripts'> & { /** * Compile-only overlay for DX: logger narrowed from unknown. */ logger: Logger; /** * Compile-only overlay for DX: dynamic map narrowed from unknown. */ dynamic?: GetDotenvDynamic; /** * Compile-only overlay for DX: scripts narrowed from Record\. */ scripts?: Scripts; }; /** * Configuration context used for generating dynamic help descriptions. * Contains merged CLI options and plugin configuration slices. * * @public */ type ResolvedHelpConfig = Partial & { /** * Per‑plugin configuration slices keyed by realized mount path * (e.g., `"aws"` or `"aws/whoami"`), used for dynamic help text. */ plugins: Record; }; /** src/cliHost/definePlugin/contracts.ts * Public contracts for plugin authoring (types only). * - No runtime logic or state. * - Safe to import broadly without introducing cycles. */ /** * Options for resolving and loading the configuration. * * @public */ interface ResolveAndLoadOptions { /** * When false, skips running plugin afterResolve hooks. * Useful for top-level help rendering to avoid long-running side-effects * while still evaluating dynamic help text. * * @default true */ runAfterResolve?: boolean; /** * Name of the invoked subcommand (plugin namespace). When provided, * only the matching plugin subtree runs afterResolve hooks. * When omitted, all plugins run afterResolve (backward compatibility). */ invokedSubcommand?: string; } /** * Structural public interface for the host exposed to plugins. * - Extends Commander.Command so plugins can attach options/commands/hooks. * - Adds host-specific helpers used by built-in plugins. * * Purpose: remove nominal class identity (private fields) from the plugin seam * to avoid TS2379 under exactOptionalPropertyTypes in downstream consumers. */ interface GetDotenvCliPublic extends Command { /** * Create a namespaced child command with argument inference. * Mirrors Commander generics so downstream chaining remains fully typed. */ ns(name: Usage, opts?: NsOptions): GetDotenvCliPublic ], {}, TOpts & TGlobal>; /** Return the current context; throws if not yet resolved. */ getCtx(): GetDotenvCliCtx; /** Check whether a context has been resolved (non-throwing). */ hasCtx(): boolean; /** * Resolve options and compute the dotenv context for this invocation. * * @param customOptions - Partial options to overlay for this invocation. * @param opts - Optional resolver behavior switches (for example, whether to run `afterResolve`). * @returns A promise resolving to the computed invocation context. */ resolveAndLoad(customOptions?: Partial, opts?: ResolveAndLoadOptions): Promise>; /** * Tag an option with a help group identifier for grouped root help rendering. * * @param opt - The Commander option to tag. * @param group - Group identifier (for example, `base`, `app`, or `plugin:`). * @returns Nothing. */ setOptionGroup(opt: Option, group: string): void; /** * Create a dynamic option whose description is computed at help time * from the resolved configuration. */ /** * Create a dynamic option whose description is computed at help time from the resolved configuration. * * @param flags - Commander option flags usage string. * @param desc - Description builder called during help rendering with the resolved help config. * @param parser - Optional argument parser. * @param defaultValue - Optional default value. * @returns A Commander `Option` instance with a dynamic description. */ createDynamicOption(flags: Usage, desc: (cfg: ResolvedHelpConfig) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option; /** {@inheritDoc} */ createDynamicOption(flags: Usage, desc: (cfg: ResolvedHelpConfig) => string, parser: (value: string, previous?: TValue) => TValue, defaultValue?: TValue): Option; } /** * Options for the `ns()` subcommand factory, forwarded to Commander's * `command(name, opts)` second argument. * * @public */ interface NsOptions { /** * When true, this subcommand becomes the default: Commander routes * unrecognized positional tokens to it when no explicit subcommand matches. */ isDefault?: boolean; /** * When true, the subcommand is hidden from help output. */ hidden?: boolean; } /** * Optional overrides for plugin composition. * * @public */ interface PluginNamespaceOverride { /** * Override the default namespace for this plugin instance. */ ns?: string; } /** * An entry in the plugin children array. * * @public */ interface PluginChildEntry { /** The child plugin instance to mount under this parent. */ plugin: GetDotenvCliPlugin; /** * Optional namespace override for the child when mounted under the parent. * When provided, this name is used instead of the child's default `ns`. */ override: PluginNamespaceOverride | undefined; } /** Public plugin contract used by the GetDotenv CLI host. */ interface GetDotenvCliPlugin { /** Namespace (required): the command name where this plugin is mounted. */ ns: string; /** * Options forwarded to the host's `ns()` call when creating the mount * for this plugin (e.g. `{ isDefault: true }`). */ nsOptions?: NsOptions; /** * Setup phase: register commands and wiring on the provided mount. * Runs parent → children (pre-order). Return nothing (void). */ setup: (cli: GetDotenvCliPublic) => void | Promise; /** * After the dotenv context is resolved, initialize any clients/secrets * or attach per-plugin state under ctx.plugins (by convention). * Runs parent → children (pre-order). * * **Scoping**: When the host provides an invoked subcommand filter, * afterResolve only fires for plugins whose namespace matches the * invoked command path. A plugin's afterResolve should never produce * side effects for commands outside its subtree. */ afterResolve?: (cli: GetDotenvCliPublic, ctx: GetDotenvCliCtx) => void | Promise; /** Zod schema for this plugin's config slice (from config.plugins[…]). */ configSchema?: ZodObject; /** * Compositional children, with optional per-child overrides (e.g., ns). * Installed after the parent per pre-order. */ children: Array>; /** * Compose a child plugin with optional override (ns). Returns the parent * to enable chaining. */ use: (child: GetDotenvCliPlugin, override?: PluginNamespaceOverride) => GetDotenvCliPlugin; } /** * Compile-time helper type: the plugin object returned by definePlugin always * includes the instance-bound helpers as required members. Keeping the public * interface optional preserves compatibility for ad-hoc/test plugins, while * return types from definePlugin provide stronger DX for shipped/typed plugins. */ interface PluginWithInstanceHelpers extends GetDotenvCliPlugin { /** * Read the validated (and interpolated) configuration slice for this plugin instance. * * @param cli - The plugin mount (or any command under this mount) used to resolve the invocation context. * @returns The plugin configuration slice, typed as `TCfg`. * @throws Error when called before the host has resolved the invocation context. */ readConfig(cli: GetDotenvCliPublic): Readonly; /** * Create a Commander option whose help-time description receives the resolved root help config * and this plugin instance’s validated configuration slice. * * @typeParam TCfg - The plugin configuration slice type. * @typeParam Usage - The Commander usage string for the option flags. * @param cli - The plugin mount used to associate the option with a realized mount path. * @param flags - Commander option flags usage string. * @param desc - Description builder receiving the resolved help config and the plugin config slice. * @param parser - Optional argument parser. * @param defaultValue - Optional default value. * @returns A Commander `Option` instance with a dynamic description. */ createPluginDynamicOption(cli: GetDotenvCliPublic, flags: Usage, desc: (cfg: ResolvedHelpConfig, pluginCfg: Readonly) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option; } /** * Public spec type for defining a plugin with compositional helpers. */ type DefineSpec = Omit, 'children' | 'use' | 'setup'> & { /** * Required namespace and setup function. The host creates the mount and * passes it into setup; return void | Promise. */ ns: string; /** * Plugin setup hook. * * Called by the host during installation to attach commands/options/hooks to the provided mount. * * @param cli - The command mount created by the host for this plugin instance. * @returns Nothing (or a promise resolving to nothing) after setup completes. */ setup: (cli: GetDotenvCliPublic) => void | Promise; }; /** * Helper to infer the configuration type from a `PluginWithInstanceHelpers` type. */ type InferPluginConfig

= P extends PluginWithInstanceHelpers ? Readonly : never; /** * Define a GetDotenv CLI plugin with compositional helpers. * * @example * const p = definePlugin(\{ ns: 'aws', setup(cli) \{ /* wire subcommands *\/ \} \}) * .use(child, \{ ns: 'whoami' \}); */ declare function definePlugin(spec: Omit, 'configSchema'> & { configSchema: Schema; }): PluginWithInstanceHelpers>; declare function definePlugin(spec: DefineSpec): PluginWithInstanceHelpers; /** * Helper to decide whether to capture child stdio. * Checks GETDOTENV_STDIO env var or the provided bag capture flag. */ declare const shouldCapture: (bagCapture?: boolean) => boolean; /** src/cliHost/GetDotenvCli.ts * Plugin-first CLI host for get-dotenv with Commander generics preserved. * Public surface implements GetDotenvCliPublic and provides: * - attachRootOptions (builder-only; no public override wiring) * - resolveAndLoad (strict resolve + context compute) * - getCtx/hasCtx accessors * - ns() for typed subcommand creation with duplicate-name guard * - grouped help rendering with dynamic option descriptions */ declare const CTX_SYMBOL: unique symbol; declare const OPTS_SYMBOL: unique symbol; declare const HELP_HEADER_SYMBOL: unique symbol; /** * Plugin-first CLI host for get-dotenv. Extends Commander.Command. * * Responsibilities: * - Resolve options strictly and compute dotenv context (resolveAndLoad). * - Expose a stable accessor for the current context (getCtx). * - Provide a namespacing helper (ns). * - Support composable plugins with parent → children install and afterResolve. */ declare class GetDotenvCli extends Command implements GetDotenvCliPublic { /** Registered top-level plugins (composition happens via .use()) */ private _plugins; /** One-time installation guard */ private _installed; /** In-flight installation promise to guard against concurrent installs */ private _installing?; /** Optional header line to prepend in help output */ private [HELP_HEADER_SYMBOL]; /** Context/options stored under symbols (typed) */ private [CTX_SYMBOL]?; private [OPTS_SYMBOL]?; /** * Create a subcommand using the same subclass, preserving helpers like * dynamicOption on children. */ createCommand(name?: string): GetDotenvCli; constructor(alias?: string); /** * Attach legacy/base root flags to this CLI instance. * Delegates to the pure builder in attachRootOptions.ts. */ attachRootOptions(defaults?: Partial): this; /** * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol. * * @param customOptions - Partial options to overlay for this invocation. * @param opts - Optional resolver behavior switches. * - `runAfterResolve` (default `true`): when false, skips running plugin * afterResolve hooks. Useful for top-level help rendering to avoid * long-running side-effects while still evaluating dynamic help text. * - `invokedSubcommand`: when provided, only the plugin subtree whose * namespace matches this name runs afterResolve hooks. When omitted, * all plugins run afterResolve (backward compatibility). */ resolveAndLoad(customOptions?: Partial, opts?: ResolveAndLoadOptions): Promise>; /** * Create a Commander Option that computes its description at help time. * The returned Option may be configured (conflicts, default, parser) and * added via addOption(). */ createDynamicOption(flags: Usage, desc: (cfg: ResolvedHelpConfig) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option; createDynamicOption(flags: Usage, desc: (cfg: ResolvedHelpConfig) => string, parser: (value: string, previous?: TValue) => TValue, defaultValue?: TValue): Option; /** * Evaluate dynamic descriptions for this command and all descendants using * the provided resolved configuration. Mutates the Option.description in * place so Commander help renders updated text. */ evaluateDynamicOptions(resolved: ResolvedHelpConfig): void; /** Internal: climb to the true root (host) command. */ private _root; /** * Retrieve the current invocation context (if any). */ getCtx(): GetDotenvCliCtx; /** * Check whether a context has been resolved (non-throwing guard). */ hasCtx(): boolean; /** * Retrieve the merged root CLI options bag (if set by passOptions()). * Downstream-safe: no generics required. */ getOptions(): GetDotenvCliOptions | undefined; /** Internal: set the merged root options bag for this run. */ _setOptionsBag(bag: GetDotenvCliOptions): void; /** * Convenience helper to create a namespaced subcommand with argument inference. * This mirrors Commander generics so downstream chaining stays fully typed. */ ns(name: Usage, opts?: NsOptions): GetDotenvCliPublic ], {}, TOpts & TGlobal>; /** * Tag options added during the provided callback as 'app' for grouped help. * Allows downstream apps to demarcate their root-level options. */ tagAppOptions(fn: (root: CommandUnknownOpts) => T): T; /** * Branding helper: set CLI name/description/version and optional help header. * If version is omitted and importMetaUrl is provided, attempts to read the * nearest package.json version (best-effort; non-fatal on failure). */ brand(args: BrandOptions): Promise; /** * Insert grouped plugin/app options between "Options" and "Commands" for * hybrid ordering. Applies to root and any parent command. */ helpInformation(): string; /** * Public: tag an Option with a display group for help (root/app/plugin:). */ setOptionGroup(opt: Option, group: string): void; /** * Register a plugin for installation (parent level). * Installation occurs on first resolveAndLoad() (or explicit install()). */ use(plugin: GetDotenvCliPlugin, override?: PluginNamespaceOverride): this; /** * Install all registered plugins in parent → children (pre-order). * Runs only once per CLI instance. */ install(): Promise; /** * Run afterResolve hooks for registered plugins (parent → children). * When {@link commandPath} is provided, only the matching branch of the * plugin tree runs; otherwise all plugins run (backward compatibility). * * The path is walked segment-by-segment against the plugin tree. * Intermediate matches run their own afterResolve hook. * The deepest match runs afterResolve for itself and all its descendants. */ _runAfterResolve(ctx: GetDotenvCliCtx, commandPath?: string[]): Promise; } /** * Options for {@link groupPlugins}. * * This helper creates a “namespace-only” parent plugin (a command that exists only * to group child plugins under a shared prefix, like `tooling getdotenv init`). * * The returned plugin is composable: call `.use(childPlugin)` to mount children. * * @typeParam TOptions - The host option bag type. * * @public */ interface GroupPluginsOptions { /** * Namespace for the grouping command (the command name used in the CLI). */ ns: string; /** * Long-form description shown when rendering help for the group command. */ description?: string; /** * Short summary shown in the parent command’s subcommand list. */ summary?: string; /** * Help group heading for this command when listed in the parent’s help output. */ helpGroup?: string; /** * Optional aliases for the group command (e.g., `['gd']`). */ aliases?: string[]; /** * Optional hook to customize the group command mount (e.g., attach a note or * a small set of options). Avoid adding actions here; keep this a group. */ configure?: (cli: GetDotenvCliPublic) => void | Promise; } /** * Create a namespace-only parent plugin (a group command) for composing plugins * under a shared prefix. * * This is a convenience wrapper around {@link definePlugin} that performs no * action by default and exists only for command organization. * * @example * ```ts * program.use( * groupPlugins({ * ns: 'getdotenv', * description: 'getdotenv utility functions', * aliases: ['gd'], * }).use(initPlugin()), * ); * ``` * * @typeParam TOptions - The host option bag type. * @param options - Group plugin options. * @returns A plugin instance that can `.use(...)` child plugins. * * @public */ declare function groupPlugins(options: GroupPluginsOptions): PluginWithInstanceHelpers; /** * Retrieve the merged root options bag from the current command context. * Climbs to the root `GetDotenvCli` instance to access the persisted options. * * @param cmd - The current command instance (thisCommand). * @throws Error if the root is not a GetDotenvCli or options are missing. */ declare const readMergedOptions: (cmd: CommandUnknownOpts) => GetDotenvCliOptions; /** * Build a sanitized environment object for spawning child processes. * Merges `base` and `overlay`, drops undefined values, and handles platform-specific * normalization (e.g. case-insensitivity on Windows). * * @param base - Base environment (usually `process.env`). * @param overlay - Environment variables to overlay. */ declare const buildSpawnEnv: (base?: NodeJS.ProcessEnv, overlay?: ProcessEnv) => NodeJS.ProcessEnv; /** * Create a get-dotenv CLI host with included plugins. * * Options: * - alias: command name used for help/argv scaffolding (default: "getdotenv") * - branding: optional help header; when omitted, brand() uses " v" * * Usage: * ```ts * import { createCli } from '@karmaniverous/get-dotenv'; * * await createCli({ * alias: 'getdotenv', * branding: 'getdotenv vX.Y.Z' * })(); * ``` */ type CreateCliOptions = { /** * CLI command name used for help and argv scaffolding. * Defaults to `'getdotenv'` when omitted. */ alias?: string; /** * Optional help header text. When omitted, brand() uses * `" v"` if a version can be read. */ branding?: string; /** * Optional composer to wire the CLI (plugins/options). If not provided, * the shipped default wiring is applied. Any `configureOutput`/`exitOverride` * you call here override the defaults. */ compose?: (program: GetDotenvCli) => GetDotenvCli; /** * Root defaults applied once before composition. These are used by flag declaration * and merge-time defaults (and top-level -h parity labels). * Note: shipped CLI does not force loadProcess OFF; base defaults apply unless set here. */ rootOptionDefaults?: Partial; /** * Visibility map to hide families/singles from root help. When a key is false, * the corresponding option(s) are hidden (via hideHelp) after flags are declared. */ rootOptionVisibility?: Partial>; }; /** * Create a configured get-dotenv CLI host. * Applies defaults, installs root hooks, and composes plugins. * Returns a runner function that accepts an argv array. */ declare function createCli(opts?: CreateCliOptions): (argv?: string[]) => Promise; /** * Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps). * Used as the bottom layer for CLI option resolution. */ /** * Script entry shape used by {@link baseRootOptionDefaults}. * * @public */ interface BaseRootOptionDefaultsScript { /** * Command string to execute. */ cmd: string; /** * Shell setting for the command. */ shell: boolean; } /** * Root defaults object exported as {@link baseRootOptionDefaults}. * * @public */ interface BaseRootOptionDefaults { /** Dotenv token indicating a dotenv file (default `.env`). */ dotenvToken: string; /** When true, load composed values into `process.env`. */ loadProcess: boolean; /** Logger used by the host and plugins (console-compatible). */ logger: Pick; /** Enable entropy warnings (presentation-only). */ warnEntropy: boolean; /** Entropy threshold (bits/char) used for warnings. */ entropyThreshold: number; /** Minimum value length to check for entropy warnings. */ entropyMinLength: number; /** Regex patterns (as strings) to suppress entropy warnings by key. */ entropyWhitelist: string[]; /** Env var name in global dotenv files that specifies the default environment. */ defaultEnvKey: string; /** Default dotenv search paths (stringly, CLI-compatible). */ paths: string; /** Paths delimiter used for the `--paths` string. */ pathsDelimiter: string; /** Token indicating private variables (default `local`). */ privateToken: string; /** Default scripts table used by cmd/batch resolution. */ scripts: Record; /** Shell preference for commands (boolean true means “default shell”). */ shell: boolean; /** Extra vars string (CLI-compatible). */ vars: string; /** Vars assignment operator for `--vars` parsing. */ varsAssignor: string; /** Vars delimiter for `--vars` parsing. */ varsDelimiter: string; } /** * Default values for root CLI options used by the host and helpers as the baseline layer during option resolution. * * These defaults correspond to the “stringly” root surface (see `RootOptionsShape`) and are merged by precedence with: * - create-time overrides * - any discovered configuration `rootOptionDefaults` * - and finally CLI flags at runtime * * @public */ declare const baseRootOptionDefaults: BaseRootOptionDefaults; /** * Configuration options for entropy analysis. * * @public */ interface EntropyOptions { /** Enable entropy warnings. */ warnEntropy?: boolean; /** Entropy threshold (bits/char). */ entropyThreshold?: number; /** Minimum string length to check. */ entropyMinLength?: number; /** Whitelist of regex patterns to ignore. */ entropyWhitelist?: Array; } /** * Maybe emit a one-line entropy warning for a key. * Caller supplies an `emit(line)` function; the helper ensures once-per-key. */ declare const maybeWarnEntropy: (key: string, value: string | undefined, origin: "dotenv" | "parent" | "unset", opts: EntropyOptions | undefined, emit: (line: string) => void) => void; /** src/diagnostics/redact.ts * Presentation-only redaction utilities for logs/trace. * - Default secret-like key patterns: SECRET, TOKEN, PASSWORD, API_KEY, KEY * - Optional custom patterns (regex strings) may be provided. * - Never alters runtime env; only affects displayed values. */ /** * Configuration options for secret redaction. * * @public */ interface RedactOptions { /** Enable redaction. */ redact?: boolean; /** Regex patterns for keys to redact. */ redactPatterns?: Array; } /** * Redact a single displayed value according to key/patterns. * Returns the original value when redaction is disabled or key is not matched. */ declare const redactDisplay: (key: string, value: string | undefined, opts?: RedactOptions) => string | undefined; /** * Produce a shallow redacted copy of an env-like object for display. */ declare const redactObject: (obj: ProcessEnv, opts?: RedactOptions) => ProcessEnv; /** * Options for tracing composed child environment variables. * * Presentation-only: values are never mutated; output is written to {@link write}. * * @public */ interface TraceChildEnvOptions extends Pick, EntropyOptions { /** * Parent process environment (source). */ parentEnv: ProcessEnv; /** * Composed dotenv map (target). */ dotenv: ProcessEnv; /** * Optional subset of keys to trace. When omitted, all keys are traced. */ keys?: string[]; /** * Sink for trace lines (e.g., write to stderr). */ write: (line: string) => void; } /** * Trace child env composition with redaction and entropy warnings. * Presentation-only: does not mutate env; writes lines via the provided sink. */ declare function traceChildEnv(opts: TraceChildEnvOptions): void; /** * Recursively expands environment variables in a string. Variables may be * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`. * Unknown variables will expand to an empty string. * * @param value - The string to expand. * @param ref - The reference object to use for variable expansion. * @returns The expanded string. * * @example * ```ts * process.env.FOO = 'bar'; * dotenvExpand('Hello $FOO'); // "Hello bar" * dotenvExpand('Hello $BAZ:world'); // "Hello world" * ``` * * @remarks * The expansion is recursive. If a referenced variable itself contains * references, those will also be expanded until a stable value is reached. * Escaped references (e.g. `\$FOO`) are preserved as literals. */ declare const dotenvExpand: (value: string | undefined, ref?: ProcessEnv) => string | undefined; /** * Options for {@link dotenvExpandAll}. * * @public */ interface DotenvExpandAllOptions { /** * The reference object to use for expansion (defaults to process.env). */ ref?: ProcessEnv; /** * Whether to progressively add expanded values to the set of reference keys. */ progressive?: boolean; } /** * Recursively expands environment variables in the values of a JSON object. * Variables may be presented with optional default as `$VAR[:default]` or * `${VAR[:default]}`. Unknown variables will expand to an empty string. * * @param values - The values object to expand. * @param options - Expansion options. * @returns The value object with expanded string values. * * @example * ```ts * process.env.FOO = 'bar'; * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' }); * // => { A: "bar", B: "xbary" } * ``` * * @remarks * Options: * - ref: The reference object to use for expansion (defaults to process.env). * - progressive: Whether to progressively add expanded values to the set of * reference keys. * * When `progressive` is true, each expanded key becomes available for * subsequent expansions in the same object (left-to-right by object key order). */ declare function dotenvExpandAll>(values: T, options?: DotenvExpandAllOptions): ProcessEnv & { [K in keyof T]: string | undefined; }; /** * Recursively expands environment variables in a string using `process.env` as * the expansion reference. Variables may be presented with optional default as * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an * empty string. * * @param value - The string to expand. * @returns The expanded string. * * @example * ```ts * process.env.FOO = 'bar'; * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar" * ``` */ declare const dotenvExpandFromProcessEnv: (value: string | undefined) => string | undefined; /** * Dotenv editor types (format-preserving). * * Requirements addressed: * - Provide a format-preserving dotenv edit surface (pure text pipeline + FS adapter). * - Preserve comments/blank lines/unknown lines and separator spacing; support merge vs sync. * - Deterministic target selection across getdotenv `paths` with optional template bootstrap. * * Notes: * - The parser intentionally preserves unknown lines verbatim rather than rejecting them. * - The editor focuses on `.env`-style KEY=VALUE lines; anything not recognized is preserved as raw text. * * @packageDocumentation */ /** * EOL policy for rendering a dotenv document. * * - `preserve`: preserve existing EOLs when possible; inserted line breaks use the detected file EOL. * - `lf`: normalize all line breaks to `\n`. * - `crlf`: normalize all line breaks to `\r\n`. * * @public */ type DotenvEolMode = 'preserve' | 'lf' | 'crlf'; /** * Editing mode for dotenv updates. * * - `merge` (default): update/add only the provided keys; do not delete unrelated keys. * - `sync`: delete assignment/bare-key lines for keys not present in the update map. * * @public */ type DotenvEditMode = 'merge' | 'sync'; /** * Strategy for handling duplicate key occurrences. * * - `all` (default): update/delete all occurrences. * - `first`: update/delete only the first occurrence. * - `last`: update/delete only the last occurrence. * * @public */ type DotenvDuplicateKeyStrategy = 'all' | 'first' | 'last'; /** * Behavior when an update map contains a key with value `undefined`. * * - `skip` (default): do not modify existing occurrences; do not add a new key. * * @public */ type DotenvUndefinedBehavior = 'skip'; /** * Behavior when an update map contains a key with value `null`. * * - `delete` (default): delete matching assignment/bare-key lines (subject to duplicate strategy). * * @public */ type DotenvNullBehavior = 'delete'; /** * Update-map value types supported by the editor. * * Notes: * - Objects/arrays are stringified with `JSON.stringify` before writing. * - `null` deletes (by default). * - `undefined` skips (by default). * * @public */ type DotenvUpdateValue = string | number | boolean | null | undefined | Record | Array; /** * Update map keyed by dotenv variable name. * * @public */ type DotenvUpdateMap = Record; /** * Options for editing a dotenv document in memory. * * @public */ interface DotenvEditOptions { /** * Editing mode (`merge` vs `sync`). * * @defaultValue `'merge'` */ mode?: DotenvEditMode; /** * Duplicate key handling strategy. * * @defaultValue `'all'` */ duplicateKeys?: DotenvDuplicateKeyStrategy; /** * `undefined` behavior. * * @defaultValue `'skip'` */ undefinedBehavior?: DotenvUndefinedBehavior; /** * `null` behavior. * * @defaultValue `'delete'` */ nullBehavior?: DotenvNullBehavior; /** * EOL normalization policy. * * @defaultValue `'preserve'` */ eol?: DotenvEolMode; /** * Separator to use when converting a bare-key placeholder into an assignment. * * @defaultValue `'='` */ defaultSeparator?: string; } /** * A raw, unrecognized segment of a dotenv file. Preserved verbatim. * * @public */ interface DotenvRawSegment { /** * Segment kind. */ kind: 'raw'; /** * Raw text (including any EOL tokens) preserved verbatim. */ raw: string; } /** * Common fields for key-bearing segments (assignment or bare-key placeholder). * * @public */ interface DotenvKeySegmentBase { /** * Raw text for the segment, including EOL tokens. */ raw: string; /** * The parsed key name (e.g., `APP_SETTING`). */ key: string; /** * Prefix before the key (indentation and optional `export` token). * Preserved verbatim. */ prefix: string; /** * Trailing EOL token for the last physical line of this segment. * For segments that end at EOF without a trailing newline, this is `''`. */ eol: '' | '\n' | '\r\n'; } /** * A KEY=VALUE assignment segment. * * Supports single-line and multi-line quoted values (double/single quotes). * * @public */ interface DotenvAssignmentSegment extends DotenvKeySegmentBase { /** * Segment kind. */ kind: 'assignment'; /** * Separator including surrounding whitespace (e.g., `" = "` or `"="`). */ separator: string; /** * Whitespace between separator and the start of the value token (preserved). */ valuePadding: string; /** * Quote style when the value was quoted in the source. */ quote: '"' | "'" | null; /** * Value content (without surrounding quotes). * * Note: multiline values use `\n` internally regardless of file EOL. */ value: string; /** * Suffix after the value token on the closing line (typically inline comment + spaces). * Preserved verbatim. */ suffix: string; } /** * A bare-key placeholder segment (e.g., `KEY` or `KEY # comment`). * * @public */ interface DotenvBareKeySegment extends DotenvKeySegmentBase { /** * Segment kind. */ kind: 'bare'; /** * Trailing text after the key (spaces and/or inline comment). * Preserved verbatim. */ suffix: string; } /** * A parsed dotenv segment. * * @public */ type DotenvSegment = DotenvRawSegment | DotenvAssignmentSegment | DotenvBareKeySegment; /** * A parsed dotenv document suitable for format-preserving edits. * * @public */ interface DotenvDocument { /** * Detected file EOL (used for inserted line breaks when preserving). */ fileEol: '\n' | '\r\n'; /** * Whether the original file ended with a trailing newline. */ trailingNewline: boolean; /** * Ordered segments comprising the file. */ segments: DotenvSegment[]; } /** * Minimal filesystem port used by the FS-level editor adapter. * * @public */ interface DotenvFs { /** * Return true when a path exists. * * @param p - Path to check. */ pathExists(p: string): Promise; /** * Read a UTF-8 text file. * * @param p - Path to read. */ readFile(p: string): Promise; /** * Write a UTF-8 text file. * * @param p - Path to write. * @param contents - File contents. */ writeFile(p: string, contents: string): Promise; /** * Copy a file. * * @param src - Source path. * @param dest - Destination path. */ copyFile(src: string, dest: string): Promise; } /** * Dotenv target scope selector for FS-level editing. * * @public */ type DotenvTargetScope = 'global' | 'env'; /** * Dotenv target privacy selector for FS-level editing. * * @public */ type DotenvTargetPrivacy = 'public' | 'private'; /** * Path search order for selecting the first target match under `paths`. * * @public */ type DotenvPathSearchOrder = 'reverse' | 'forward'; /** * Options for resolving and editing a dotenv file in a multi-path cascade. * * @public */ interface EditDotenvFileOptions extends DotenvEditOptions { /** * Search paths (directories) to locate the target dotenv file. */ paths: string[]; /** * Base dotenv filename token. * * @defaultValue `'.env'` */ dotenvToken?: string; /** * Private token used for private dotenv files. * * @defaultValue `'local'` */ privateToken?: string; /** * Selected environment name (used when `scope` is `env`). */ env?: string; /** * Default environment name used when `env` is not provided. */ defaultEnv?: string; /** * Scope axis (global vs env-specific). */ scope: DotenvTargetScope; /** * Privacy axis (public vs private). */ privacy: DotenvTargetPrivacy; /** * Path search order. * * @defaultValue `'reverse'` */ searchOrder?: DotenvPathSearchOrder; /** * Template extension used for bootstrap. * * When a target does not exist anywhere under `paths`, but a template exists * (e.g. `.env.local.template`), the template will be copied to the target * path and then edited in place. * * @defaultValue `'template'` */ templateExtension?: string; /** * Optional filesystem port override (defaults to a Node FS adapter). */ fs?: DotenvFs; } /** * Result of a successful FS-level dotenv edit. * * @public */ interface EditDotenvFileResult { /** * Absolute path to the edited dotenv file. */ path: string; /** * Whether the file was created from a template during this operation. */ createdFromTemplate: boolean; /** * Whether the resulting file content differed from the prior content. */ changed: boolean; } /** * Apply edits to a parsed dotenv document while preserving formatting. * * Requirements addressed: * - Mode: merge vs sync. * - Duplicate key strategy: all/first/last. * - undefined behavior: skip (default). * - null behavior: delete (default). * - Quote preservation where safe; upgrade quoting when required (multiline, whitespace safety, inline comment safety). * * @packageDocumentation */ /** * Apply a set of key/value updates to a parsed dotenv document. * * @param doc - Parsed dotenv document. * @param updates - Key/value update map. * @param opts - Editing options. * @returns A new {@link DotenvDocument} with edits applied. * * @public */ declare function applyDotenvEdits(doc: DotenvDocument, updates: DotenvUpdateMap, opts?: { mode?: DotenvEditMode; duplicateKeys?: DotenvDuplicateKeyStrategy; undefinedBehavior?: DotenvUndefinedBehavior; nullBehavior?: DotenvNullBehavior; defaultSeparator?: string; }): DotenvDocument; /** * FS-level dotenv editor adapter (target resolution + template bootstrap). * * Requirements addressed: * - Deterministic target selection across getdotenv `paths` only. * - Scope axis (global|env) × privacy axis (public|private). * - Template bootstrap: copy `.` to `` when needed. * - Edit in place while preserving formatting via the pure text editor. * * @packageDocumentation */ /** * Edit a dotenv file selected by scope/privacy across a list of search paths. * * @param updates - Update map of keys to values. * @param options - Target selection options + edit options. * @returns An {@link EditDotenvFileResult}. * * @public */ declare function editDotenvFile(updates: DotenvUpdateMap, options: EditDotenvFileOptions): Promise; /** * High-level convenience API for editing dotenv text in memory. * * Requirements addressed: * - Pure/text layer: parse → apply edits → render (no FS). * * @packageDocumentation */ /** * Edit dotenv text with format preservation. * * @param text - Existing dotenv text. * @param updates - Update map of keys to values. * @param options - Edit options (merge vs sync, duplicates, null/undefined behavior, EOL policy). * @returns Updated dotenv text. * * @public */ declare function editDotenvText(text: string, updates: DotenvUpdateMap, options?: DotenvEditOptions): string; /** * Parse a dotenv file into a format-preserving document model. * * Requirements addressed: * - Preserve comments, blank lines, ordering, and unknown lines verbatim. * - Preserve separator spacing around `=`. * - Support multiline quoted values (double/single quotes) by grouping physical lines. * * @packageDocumentation */ /** * Parse dotenv text into a document model that preserves formatting. * * @param text - Dotenv file contents as UTF-8 text. * @returns A parsed {@link DotenvDocument}. * * @public */ declare function parseDotenvDocument(text: string): DotenvDocument; /** * Render a parsed dotenv document back to text. * * Requirements addressed: * - Preserve existing EOLs by default; support forcing LF/CRLF. * - Preserve trailing newline presence/absence. * * @packageDocumentation */ /** * Render a {@link DotenvDocument} to text. * * @param doc - Document to render. * @param eolMode - EOL policy (`preserve` | `lf` | `crlf`). * @returns Rendered dotenv text. * * @public */ declare function renderDotenvDocument(doc: DotenvDocument, eolMode?: DotenvEolMode): string; /** * Filter an environment object using include/exclude lists. * * - If `exclude` is provided, keys in the list are removed. * - If `include` is provided, only keys in the list are kept (applied after exclusion). * * @param env - Source environment object. * @param options - Filtering options (include/exclude lists). * @returns A new environment object with keys filtered. */ declare const applyIncludeExclude: (env: ProcessEnv, { include, exclude, }: { include?: string[]; exclude?: string[]; }) => ProcessEnv; /** * Assert that a value is a non-empty string. * * @param v - Value to check. * @param msg - Error message to throw if check fails. */ declare const requireString: (v: unknown, msg: string) => string; /** * Assert that the byte length of a value (stringified) does not exceed a limit. * * @param value - Value to measure (strings used as-is; others JSON-stringified). * @param limit - Maximum allowed byte length. * @param errorMsg - Error message string or generator function. */ declare const assertByteLimit: (value: unknown, limit: number, errorMsg: string | ((v: unknown, l: number) => string)) => void; /** * Perform a deep defaults‑style merge across plain objects. * - Only merges plain objects (prototype === Object.prototype). * - Arrays and non‑objects are replaced, not merged. * - `undefined` values are ignored and do not overwrite prior values. * * @typeParam T - Resulting shape after merging all layers. * @returns The merged object typed as T. * * @example * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \}) * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \} */ declare function defaultsDeep(a?: Partial): A; declare function defaultsDeep(a?: Partial, b?: Partial): A & B; declare function defaultsDeep(a?: Partial, b?: Partial, c?: Partial): A & B & C; declare function defaultsDeep(a?: Partial, b?: Partial, c?: Partial, d?: Partial): A & B & C & D; declare function defaultsDeep(a?: Partial, b?: Partial, c?: Partial, d?: Partial, e?: Partial): A & B & C & D & E; declare function defaultsDeep(...layers: Array | undefined>): T; /** * Serialize a dotenv record to a file with minimal quoting (multiline values are quoted). * Future-proofs for ordering/sorting changes (currently insertion order). * * @param filename - Destination dotenv file path. * @param data - Env-like map of values to write (values may be `undefined`). * @returns A `Promise\` which resolves when the file has been written. */ declare function writeDotenvFile(filename: string, data: ProcessEnv): Promise; /** * Deeply interpolate string leaves against envRef. * Arrays are not recursed into; they are returned unchanged. * * @typeParam T - Shape of the input value. * @param value - Input value (object/array/primitive). * @param envRef - Reference environment for interpolation. * @returns A new value with string leaves interpolated. */ declare const interpolateDeep: (value: T, envRef: ProcessEnv) => T; /** * Load a module default export from a JS/TS file with robust fallbacks. * * Behavior by extension: * * - `.js`/`.mjs`/`.cjs`: direct dynamic import. * - `.ts`/`.mts`/`.cts`/`.tsx`: * - try direct dynamic import (when a TS loader is active), * - else compile via `esbuild` to a cached `.mjs` file and import, * - else fallback to `typescript.transpileModule` for simple modules. * * @typeParam T - Type of the expected default export. * @param absPath - Absolute path to the source file. * @param cacheDirName - Cache subfolder under `.tsbuild/`. * @returns A `Promise\` resolving to the default export (if any). */ declare const loadModuleDefault: (absPath: string, cacheDirName: string) => Promise; /** * A silent logger that implements the Logger interface but performs no operations. */ declare const silentLogger: Logger; /** * Parse a value into a number or undefined. * * @param v - Value to parse. * @returns The parsed number, or undefined if the input was undefined or empty string. */ declare const toNumber: (v: unknown) => number | undefined; /** * Build a Commander option parser that coerces a raw string to a finite number. * * @param label - Label used in error messages (e.g. `"port"`). * @returns Parser suitable for Commander `.option(..., parser)`. */ declare const parseFiniteNumber: (label: string) => (raw: string) => number; /** * Build a Commander option parser that coerces a raw string to a positive integer. * * @param label - Label used in error messages (e.g. `"maxSeconds"`). * @returns Parser suitable for Commander `.option(..., parser)`. */ declare const parsePositiveInt: (label: string) => (raw: string) => number; /** * Build a Commander option parser that coerces a raw string to a non-negative integer. * * @param label - Label used in error messages (e.g. `"limit"`). * @returns Parser suitable for Commander `.option(..., parser)`. */ declare const parseNonNegativeInt: (label: string) => (raw: string) => number; /** * Options for the tokenizer used by shell-off command handling. * * @public */ interface TokenizeOptions { /** * When true, keep doubled quotes inside a quoted segment (e.g., `""` stays `""`), * which is useful for preserving Node -e payload quoting patterns. * When false (default), doubled quotes collapse to a single literal quote. */ preserveDoubledQuotes?: boolean; } /** * Minimal tokenizer for shell-off execution. * Splits by whitespace while preserving quoted segments (single or double quotes). * * @param command - The command string to tokenize. * @param opts - Tokenization options (e.g. quote handling). */ declare const tokenize: (command: string, opts?: TokenizeOptions) => string[]; export { GetDotenvCli, applyDotenvEdits, applyIncludeExclude, assertByteLimit, assertLogger, baseRootOptionDefaults, buildSpawnEnv, createCli, defaultsDeep, defineDynamic, defineGetDotenvConfig, definePlugin, defineScripts, dotenvExpand, dotenvExpandAll, dotenvExpandFromProcessEnv, editDotenvFile, editDotenvText, getDotenv, getDotenvCliOptions2Options, groupPlugins, interpolateDeep, loadModuleDefault, maybeWarnEntropy, parseDotenvDocument, parseFiniteNumber, parseNonNegativeInt, parsePositiveInt, readMergedOptions, redactDisplay, redactObject, renderDotenvDocument, requireString, shouldCapture, silentLogger, toNumber, tokenize, traceChildEnv, writeDotenvFile }; export type { CreateCliOptions, DotenvAssignmentSegment, DotenvBareKeySegment, DotenvConfigProvenanceEntry, DotenvDocument, DotenvDuplicateKeyStrategy, DotenvDynamicProvenanceEntry, DotenvDynamicSource, DotenvEditMode, DotenvEditOptions, DotenvEolMode, DotenvFileProvenanceEntry, DotenvFs, DotenvPathSearchOrder, DotenvProvenance, DotenvProvenanceEntry, DotenvProvenanceEntryBase, DotenvProvenanceKind, DotenvProvenanceOp, DotenvSegment, DotenvTargetPrivacy, DotenvTargetScope, DotenvUpdateMap, DotenvUpdateValue, DotenvVarsProvenanceEntry, DynamicFn, DynamicMap, EditDotenvFileOptions, EditDotenvFileResult, EntropyOptions, GetDotenvCliOptions, GetDotenvCliPlugin, GetDotenvCliPublic, GetDotenvConfig, GetDotenvDynamic, GetDotenvOptions, InferGetDotenvVarsFromConfig, InferPluginConfig, Logger, PluginWithInstanceHelpers, ProcessEnv, RedactOptions, ScriptsTable, TokenizeOptions, TraceChildEnvOptions };