@karmaniverous/get-dotenv 5.2.4 → 5.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cliHost.mjs CHANGED
@@ -1,40 +1,264 @@
1
- import { Command } from 'commander';
1
+ import { Option, Command } from 'commander';
2
2
  import fs from 'fs-extra';
3
3
  import { packageDirectory } from 'package-directory';
4
- import url, { fileURLToPath, pathToFileURL } from 'url';
5
4
  import path, { join, extname } from 'path';
6
- import { z } from 'zod';
5
+ import url, { fileURLToPath, pathToFileURL } from 'url';
7
6
  import YAML from 'yaml';
7
+ import { z } from 'zod';
8
8
  import { nanoid } from 'nanoid';
9
9
  import { parse } from 'dotenv';
10
10
  import { createHash } from 'crypto';
11
11
 
12
- /** src/cliHost/definePlugin.ts
13
- * Plugin contracts for the GetDotenv CLI host.
12
+ /**
13
+ * Dotenv expansion utilities.
14
14
  *
15
- * This module exposes a structural public interface for the host that plugins
16
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
17
- * nominal class identity issues (private fields) in downstream consumers.
15
+ * This module implements recursive expansion of environment-variable
16
+ * references in strings and records. It supports both whitespace and
17
+ * bracket syntaxes with optional defaults:
18
+ *
19
+ * - Whitespace: `$VAR[:default]`
20
+ * - Bracketed: `${VAR[:default]}`
21
+ *
22
+ * Escaped dollar signs (`\$`) are preserved.
23
+ * Unknown variables resolve to empty string unless a default is provided.
18
24
  */
19
25
  /**
20
- * Define a GetDotenv CLI plugin with compositional helpers.
26
+ * Like String.prototype.search but returns the last index.
27
+ * @internal
28
+ */
29
+ const searchLast = (str, rgx) => {
30
+ const matches = Array.from(str.matchAll(rgx));
31
+ return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
32
+ };
33
+ const replaceMatch = (value, match, ref) => {
34
+ /**
35
+ * @internal
36
+ */
37
+ const group = match[0];
38
+ const key = match[1];
39
+ const defaultValue = match[2];
40
+ if (!key)
41
+ return value;
42
+ const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
43
+ return interpolate(replacement, ref);
44
+ };
45
+ const interpolate = (value = '', ref = {}) => {
46
+ /**
47
+ * @internal
48
+ */
49
+ // if value is falsy, return it as is
50
+ if (!value)
51
+ return value;
52
+ // get position of last unescaped dollar sign
53
+ const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
54
+ // return value if none found
55
+ if (lastUnescapedDollarSignIndex === -1)
56
+ return value;
57
+ // evaluate the value tail
58
+ const tail = value.slice(lastUnescapedDollarSignIndex);
59
+ // find whitespace pattern: $KEY:DEFAULT
60
+ const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
61
+ const whitespaceMatch = whitespacePattern.exec(tail);
62
+ if (whitespaceMatch != null)
63
+ return replaceMatch(value, whitespaceMatch, ref);
64
+ else {
65
+ // find bracket pattern: ${KEY:DEFAULT}
66
+ const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
67
+ const bracketMatch = bracketPattern.exec(tail);
68
+ if (bracketMatch != null)
69
+ return replaceMatch(value, bracketMatch, ref);
70
+ }
71
+ return value;
72
+ };
73
+ /**
74
+ * Recursively expands environment variables in a string. Variables may be
75
+ * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
76
+ * Unknown variables will expand to an empty string.
77
+ *
78
+ * @param value - The string to expand.
79
+ * @param ref - The reference object to use for variable expansion.
80
+ * @returns The expanded string.
21
81
  *
22
82
  * @example
23
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
24
- * .use(childA)
25
- * .use(childB);
83
+ * ```ts
84
+ * process.env.FOO = 'bar';
85
+ * dotenvExpand('Hello $FOO'); // "Hello bar"
86
+ * dotenvExpand('Hello $BAZ:world'); // "Hello world"
87
+ * ```
88
+ *
89
+ * @remarks
90
+ * The expansion is recursive. If a referenced variable itself contains
91
+ * references, those will also be expanded until a stable value is reached.
92
+ * Escaped references (e.g. `\$FOO`) are preserved as literals.
26
93
  */
27
- const definePlugin = (spec) => {
28
- const { children = [], ...rest } = spec;
29
- const plugin = {
30
- ...rest,
31
- children: [...children],
32
- use(child) {
33
- this.children.push(child);
34
- return this;
35
- },
94
+ const dotenvExpand = (value, ref = process.env) => {
95
+ const result = interpolate(value, ref);
96
+ return result ? result.replace(/\\\$/g, '$') : undefined;
97
+ };
98
+ /**
99
+ * Recursively expands environment variables in the values of a JSON object.
100
+ * Variables may be presented with optional default as `$VAR[:default]` or
101
+ * `${VAR[:default]}`. Unknown variables will expand to an empty string.
102
+ *
103
+ * @param values - The values object to expand.
104
+ * @param options - Expansion options.
105
+ * @returns The value object with expanded string values.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * process.env.FOO = 'bar';
110
+ * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
111
+ * // => { A: "bar", B: "xbary" }
112
+ * ```
113
+ *
114
+ * @remarks
115
+ * Options:
116
+ * - ref: The reference object to use for expansion (defaults to process.env).
117
+ * - progressive: Whether to progressively add expanded values to the set of
118
+ * reference keys.
119
+ *
120
+ * When `progressive` is true, each expanded key becomes available for
121
+ * subsequent expansions in the same object (left-to-right by object key order).
122
+ */
123
+ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
124
+ const { ref = process.env, progressive = false } = options;
125
+ acc[key] = dotenvExpand(values[key], {
126
+ ...ref,
127
+ ...(progressive ? acc : {}),
128
+ });
129
+ return acc;
130
+ }, {});
131
+ /**
132
+ * Recursively expands environment variables in a string using `process.env` as
133
+ * the expansion reference. Variables may be presented with optional default as
134
+ * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
135
+ * empty string.
136
+ *
137
+ * @param value - The string to expand.
138
+ * @returns The expanded string.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * process.env.FOO = 'bar';
143
+ * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
144
+ * ```
145
+ */
146
+ const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
147
+
148
+ /**
149
+ * Attach legacy root flags to a Commander program.
150
+ * Uses provided defaults to render help labels without coupling to generators.
151
+ */
152
+ const attachRootOptions = (program, defaults, opts) => {
153
+ // Install temporary wrappers to tag all options added here as "base".
154
+ const GROUP = 'base';
155
+ const tagLatest = (cmd, group) => {
156
+ const optsArr = cmd.options;
157
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
158
+ const last = optsArr[optsArr.length - 1];
159
+ last.__group = group;
160
+ }
36
161
  };
37
- return plugin;
162
+ const originalAddOption = program.addOption.bind(program);
163
+ const originalOption = program.option.bind(program);
164
+ program.addOption = function patchedAdd(opt) {
165
+ // Tag before adding, in case consumers inspect the Option directly.
166
+ opt.__group = GROUP;
167
+ const ret = originalAddOption(opt);
168
+ return ret;
169
+ };
170
+ program.option = function patchedOption(...args) {
171
+ const ret = originalOption(...args);
172
+ tagLatest(this, GROUP);
173
+ return ret;
174
+ };
175
+ const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
176
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
177
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
178
+ // Build initial chain.
179
+ let p = program
180
+ .enablePositionalOptions()
181
+ .passThroughOptions()
182
+ .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
183
+ p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
184
+ ['KEY1', 'VAL1'],
185
+ ['KEY2', 'VAL2'],
186
+ ]
187
+ .map((v) => v.join(va))
188
+ .join(vd)}`, dotenvExpandFromProcessEnv);
189
+ // Optional legacy root command flag (kept for generated CLI compatibility).
190
+ // Default is OFF; the generator opts in explicitly.
191
+ if (opts?.includeCommandOption === true) {
192
+ p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
193
+ }
194
+ p = p
195
+ .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
196
+ .addOption(new Option('-s, --shell [string]', (() => {
197
+ let defaultLabel = '';
198
+ if (shell !== undefined) {
199
+ if (typeof shell === 'boolean') {
200
+ defaultLabel = ' (default OS shell)';
201
+ }
202
+ else if (typeof shell === 'string') {
203
+ // Safe string interpolation
204
+ defaultLabel = ` (default ${shell})`;
205
+ }
206
+ }
207
+ return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
208
+ })()).conflicts('shellOff'))
209
+ .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
210
+ .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
211
+ .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
212
+ .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
213
+ ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
214
+ ? ' (default)'
215
+ : ''}`).conflicts('excludeAllOff'))
216
+ .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
217
+ .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
218
+ .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
219
+ .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
220
+ .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
221
+ .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
222
+ .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
223
+ .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
224
+ .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
225
+ .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
226
+ .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
227
+ .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
228
+ .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
229
+ .option('--capture', 'capture child process stdio for commands (tests/CI)')
230
+ .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
231
+ .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
232
+ .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
233
+ .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
234
+ .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
235
+ .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
236
+ .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
237
+ .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
238
+ .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
239
+ .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
240
+ .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
241
+ .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
242
+ // Hidden scripts pipe-through (stringified)
243
+ .addOption(new Option('--scripts <string>')
244
+ .default(JSON.stringify(scripts))
245
+ .hideHelp());
246
+ // Diagnostics: opt-in tracing; optional variadic keys after the flag.
247
+ p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
248
+ // Validation: strict mode fails on env validation issues (warn by default).
249
+ p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
250
+ // Entropy diagnostics (presentation-only)
251
+ p = p
252
+ .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
253
+ .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
254
+ .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
255
+ .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
256
+ .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
257
+ .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
258
+ // Restore original methods to avoid tagging future additions outside base.
259
+ program.addOption = originalAddOption;
260
+ program.option = originalOption;
261
+ return p;
38
262
  };
39
263
 
40
264
  // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
@@ -64,8 +288,6 @@ const baseRootOptionDefaults = {
64
288
  // (debug/log/exclude* resolved via flag utils)
65
289
  };
66
290
 
67
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
68
-
69
291
  /** @internal */
70
292
  const isPlainObject$1 = (value) => value !== null &&
71
293
  typeof value === 'object' &&
@@ -108,134 +330,130 @@ const defaultsDeep = (...layers) => {
108
330
  return result;
109
331
  };
110
332
 
111
- // src/GetDotenvOptions.ts
112
- const getDotenvOptionsFilename = 'getdotenv.config.json';
113
333
  /**
114
- * Converts programmatic CLI options to `getDotenv` options. *
115
- * @param cliOptions - CLI options. Defaults to `{}`.
334
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
335
+ * - If the user explicitly enabled the flag, return true.
336
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
337
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
116
338
  *
117
- * @returns `getDotenv` options.
339
+ * @param exclude - The "on" flag value as parsed by Commander.
340
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
341
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
342
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
343
+ *
344
+ * @example
345
+ * ```ts
346
+ * resolveExclusion(undefined, undefined, true); // => true
347
+ * ```
118
348
  */
119
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
120
- /**
121
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
122
- *
123
- * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
124
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
125
- * - Drops CLI-only keys that have no programmatic equivalent.
126
- *
127
- * @remarks
128
- * Follows exact-optional semantics by not emitting undefined-valued entries.
129
- */
130
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
131
- // Create a shallow copy then delete optional CLI-only keys if present.
132
- const restObj = { ...rest };
133
- delete restObj.debug;
134
- delete restObj.scripts;
135
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
136
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
137
- let parsedVars;
138
- if (typeof vars === 'string') {
139
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
140
- ? RegExp(varsAssignorPattern)
141
- : (varsAssignor ?? '=')));
142
- parsedVars = Object.fromEntries(kvPairs);
143
- }
144
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
145
- // Keep only string or undefined values to match ProcessEnv.
146
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
147
- parsedVars = Object.fromEntries(entries);
148
- }
149
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
150
- // expectations and the compat test assertions.
151
- if (parsedVars) {
152
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
153
- }
154
- // Tolerate paths as either a delimited string or string[]
155
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
156
- // under the RootOptionsShape (which declares paths as string | undefined).
157
- const pathsAny = paths;
158
- const pathsOut = Array.isArray(pathsAny)
159
- ? pathsAny.filter((p) => typeof p === 'string')
160
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
161
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
162
- return {
163
- ...restObj,
164
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
165
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
166
- };
167
- };
168
- const resolveGetDotenvOptions = async (customOptions) => {
169
- /**
170
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
171
- *
172
- * 1. Base defaults derived from the CLI generator defaults
173
- * ({@link baseGetDotenvCliOptions}).
174
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
175
- * package root (if present).
176
- * 3. The provided {@link customOptions}.
177
- *
178
- * The result preserves explicit empty values and drops only `undefined`.
179
- *
180
- * @returns Fully-resolved {@link GetDotenvOptions}.
181
- *
182
- * @example
183
- * ```ts
184
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
185
- * ```
186
- */
187
- const localPkgDir = await packageDirectory();
188
- const localOptionsPath = localPkgDir
189
- ? join(localPkgDir, getDotenvOptionsFilename)
190
- : undefined;
191
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
192
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
193
- : {});
194
- // Merge order: base < local < custom (custom has highest precedence)
195
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
196
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
197
- const result = defaultsDeep(defaultsFromCli, customOptions);
198
- return {
199
- ...result, // Keep explicit empty strings/zeros; drop only undefined
200
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
201
- };
349
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
350
+ /**
351
+ * Resolve an optional flag with "--exclude-all" overrides.
352
+ * If excludeAll is set and the individual "...-off" is not, force true.
353
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
354
+ * Otherwise, adopt the default (true set; false/undefined unset).
355
+ *
356
+ * @param exclude - Individual include/exclude flag.
357
+ * @param excludeOff - Individual "...-off" flag.
358
+ * @param defaultValue - Default for the individual flag.
359
+ * @param excludeAll - Global "exclude-all" flag.
360
+ * @param excludeAllOff - Global "exclude-all-off" flag.
361
+ *
362
+ * @example
363
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
364
+ */
365
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
366
+ // Order of precedence:
367
+ // 1) Individual explicit "on" wins outright.
368
+ // 2) Individual explicit "off" wins over any global.
369
+ // 3) Global exclude-all forces true when not explicitly turned off.
370
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
371
+ // 5) Fall back to the default (true => set; false/undefined => unset).
372
+ (() => {
373
+ // Individual "on"
374
+ if (exclude === true)
375
+ return true;
376
+ // Individual "off"
377
+ if (excludeOff === true)
378
+ return undefined;
379
+ // Global "exclude-all" ON (unless explicitly turned off)
380
+ if (excludeAll === true)
381
+ return true;
382
+ // Global "exclude-all-off" (unless explicitly enabled)
383
+ if (excludeAllOff === true)
384
+ return undefined;
385
+ // Default
386
+ return defaultValue ? true : undefined;
387
+ })();
388
+ /**
389
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
390
+ * delete when undefined; assign when defined — without requiring an index signature on T.
391
+ *
392
+ * @typeParam T - Target object type.
393
+ * @param obj - The object to write to.
394
+ * @param key - The optional boolean property key of {@link T}.
395
+ * @param value - The value to set or `undefined` to unset.
396
+ *
397
+ * @remarks
398
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
399
+ */
400
+ const setOptionalFlag = (obj, key, value) => {
401
+ const target = obj;
402
+ const k = key;
403
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
404
+ if (value === undefined)
405
+ delete target[k];
406
+ else
407
+ target[k] = value;
202
408
  };
203
409
 
204
410
  /**
205
- * Zod schemas for programmatic GetDotenv options.
206
- *
207
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
208
- * Legacy paths continue to use existing types/logic. The new plugin host will
209
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
210
- * later per the staged plan.
411
+ * Merge and normalize raw Commander options (current + parent + defaults)
412
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
413
+ * avoid cross-layer coupling; callers may cast as needed.
211
414
  */
212
- // Minimal process env representation: string values or undefined to indicate "unset".
213
- const processEnvSchema = z.record(z.string(), z.string().optional());
214
- // RAW: all fields optional — undefined means "inherit" from lower layers.
215
- const getDotenvOptionsSchemaRaw = z.object({
216
- defaultEnv: z.string().optional(),
217
- dotenvToken: z.string().optional(),
218
- dynamicPath: z.string().optional(),
219
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
220
- dynamic: z.record(z.string(), z.unknown()).optional(),
221
- env: z.string().optional(),
222
- excludeDynamic: z.boolean().optional(),
223
- excludeEnv: z.boolean().optional(),
224
- excludeGlobal: z.boolean().optional(),
225
- excludePrivate: z.boolean().optional(),
226
- excludePublic: z.boolean().optional(),
227
- loadProcess: z.boolean().optional(),
228
- log: z.boolean().optional(),
229
- outputPath: z.string().optional(),
230
- paths: z.array(z.string()).optional(),
231
- privateToken: z.string().optional(),
232
- vars: processEnvSchema.optional(),
233
- // Host-only feature flag: guarded integration of config loader/overlay
234
- useConfigLoader: z.boolean().optional(),
235
- });
236
- // RESOLVED: service-boundary contract (post-inheritance).
237
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
238
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
415
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
416
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
417
+ ? JSON.parse(parentJson)
418
+ : undefined;
419
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
420
+ const current = { ...rest };
421
+ if (typeof scripts === 'string') {
422
+ try {
423
+ current.scripts = JSON.parse(scripts);
424
+ }
425
+ catch {
426
+ // ignore parse errors; leave scripts undefined
427
+ }
428
+ }
429
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
430
+ const d = defaults;
431
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
432
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
433
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
434
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
435
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
436
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
437
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
438
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
439
+ // warnEntropy (tri-state)
440
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
441
+ // Normalize shell for predictability: explicit default shell per OS.
442
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
443
+ let resolvedShell = merged.shell;
444
+ if (shellOff)
445
+ resolvedShell = false;
446
+ else if (resolvedShell === true || resolvedShell === undefined) {
447
+ resolvedShell = defaultShell;
448
+ }
449
+ else if (typeof resolvedShell !== 'string' &&
450
+ typeof defaults.shell === 'string') {
451
+ resolvedShell = defaults.shell;
452
+ }
453
+ merged.shell = resolvedShell;
454
+ const cmd = typeof command === 'string' ? command : undefined;
455
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
456
+ };
239
457
 
240
458
  /**
241
459
  * Zod schemas for configuration files discovered by the new loader.
@@ -458,141 +676,208 @@ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
458
676
  const discovered = await discoverConfigFiles(importMetaUrl);
459
677
  const result = {};
460
678
  for (const f of discovered) {
461
- const cfg = await loadConfigFile(f.path);
462
- if (f.scope === 'packaged') {
463
- // packaged public only
464
- result.packaged = cfg;
465
- }
466
- else {
467
- result.project ??= {};
468
- if (f.privacy === 'public')
469
- result.project.public = cfg;
470
- else
471
- result.project.local = cfg;
472
- }
473
- }
474
- return result;
475
- };
476
-
477
- /**
478
- * Dotenv expansion utilities.
479
- *
480
- * This module implements recursive expansion of environment-variable
481
- * references in strings and records. It supports both whitespace and
482
- * bracket syntaxes with optional defaults:
483
- *
484
- * - Whitespace: `$VAR[:default]`
485
- * - Bracketed: `${VAR[:default]}`
486
- *
487
- * Escaped dollar signs (`\$`) are preserved.
488
- * Unknown variables resolve to empty string unless a default is provided.
489
- */
490
- /**
491
- * Like String.prototype.search but returns the last index.
492
- * @internal
493
- */
494
- const searchLast = (str, rgx) => {
495
- const matches = Array.from(str.matchAll(rgx));
496
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
497
- };
498
- const replaceMatch = (value, match, ref) => {
499
- /**
500
- * @internal
501
- */
502
- const group = match[0];
503
- const key = match[1];
504
- const defaultValue = match[2];
505
- if (!key)
506
- return value;
507
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
508
- return interpolate(replacement, ref);
509
- };
510
- const interpolate = (value = '', ref = {}) => {
511
- /**
512
- * @internal
513
- */
514
- // if value is falsy, return it as is
515
- if (!value)
516
- return value;
517
- // get position of last unescaped dollar sign
518
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
519
- // return value if none found
520
- if (lastUnescapedDollarSignIndex === -1)
521
- return value;
522
- // evaluate the value tail
523
- const tail = value.slice(lastUnescapedDollarSignIndex);
524
- // find whitespace pattern: $KEY:DEFAULT
525
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
526
- const whitespaceMatch = whitespacePattern.exec(tail);
527
- if (whitespaceMatch != null)
528
- return replaceMatch(value, whitespaceMatch, ref);
529
- else {
530
- // find bracket pattern: ${KEY:DEFAULT}
531
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
532
- const bracketMatch = bracketPattern.exec(tail);
533
- if (bracketMatch != null)
534
- return replaceMatch(value, bracketMatch, ref);
679
+ const cfg = await loadConfigFile(f.path);
680
+ if (f.scope === 'packaged') {
681
+ // packaged public only
682
+ result.packaged = cfg;
683
+ }
684
+ else {
685
+ result.project ??= {};
686
+ if (f.privacy === 'public')
687
+ result.project.public = cfg;
688
+ else
689
+ result.project.local = cfg;
690
+ }
535
691
  }
536
- return value;
692
+ return result;
537
693
  };
694
+
538
695
  /**
539
- * Recursively expands environment variables in a string. Variables may be
540
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
541
- * Unknown variables will expand to an empty string.
542
- *
543
- * @param value - The string to expand.
544
- * @param ref - The reference object to use for variable expansion.
545
- * @returns The expanded string.
546
- *
547
- * @example
548
- * ```ts
549
- * process.env.FOO = 'bar';
550
- * dotenvExpand('Hello $FOO'); // "Hello bar"
551
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
552
- * ```
696
+ * Validate a composed env against config-provided validation surfaces.
697
+ * Precedence for validation definitions:
698
+ * project.local -\> project.public -\> packaged
553
699
  *
554
- * @remarks
555
- * The expansion is recursive. If a referenced variable itself contains
556
- * references, those will also be expanded until a stable value is reached.
557
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
700
+ * Behavior:
701
+ * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
702
+ * - Else if `requiredKeys` is present, check presence (value !== undefined).
703
+ * - Returns a flat list of issue strings; caller decides warn vs fail.
558
704
  */
559
- const dotenvExpand = (value, ref = process.env) => {
560
- const result = interpolate(value, ref);
561
- return result ? result.replace(/\\\$/g, '$') : undefined;
705
+ const validateEnvAgainstSources = (finalEnv, sources) => {
706
+ const pick = (getter) => {
707
+ const pl = sources.project?.local;
708
+ const pp = sources.project?.public;
709
+ const pk = sources.packaged;
710
+ return ((pl && getter(pl)) ||
711
+ (pp && getter(pp)) ||
712
+ (pk && getter(pk)) ||
713
+ undefined);
714
+ };
715
+ const schema = pick((cfg) => cfg['schema']);
716
+ if (schema &&
717
+ typeof schema.safeParse === 'function') {
718
+ try {
719
+ const parsed = schema.safeParse(finalEnv);
720
+ if (!parsed.success) {
721
+ // Try to render zod-style issues when available.
722
+ const err = parsed.error;
723
+ const issues = Array.isArray(err.issues) && err.issues.length > 0
724
+ ? err.issues.map((i) => {
725
+ const path = Array.isArray(i.path) ? i.path.join('.') : '';
726
+ const msg = i.message ?? 'Invalid value';
727
+ return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
728
+ })
729
+ : ['[schema] validation failed'];
730
+ return issues;
731
+ }
732
+ return [];
733
+ }
734
+ catch {
735
+ // If schema invocation fails, surface a single diagnostic.
736
+ return [
737
+ '[schema] validation failed (unable to execute schema.safeParse)',
738
+ ];
739
+ }
740
+ }
741
+ const requiredKeys = pick((cfg) => cfg['requiredKeys']);
742
+ if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
743
+ const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
744
+ if (missing.length > 0) {
745
+ return missing.map((k) => `[requiredKeys] missing: ${k}`);
746
+ }
747
+ }
748
+ return [];
562
749
  };
750
+
751
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
752
+
753
+ // src/GetDotenvOptions.ts
754
+ const getDotenvOptionsFilename = 'getdotenv.config.json';
563
755
  /**
564
- * Recursively expands environment variables in the values of a JSON object.
565
- * Variables may be presented with optional default as `$VAR[:default]` or
566
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
567
- *
568
- * @param values - The values object to expand.
569
- * @param options - Expansion options.
570
- * @returns The value object with expanded string values.
571
- *
572
- * @example
573
- * ```ts
574
- * process.env.FOO = 'bar';
575
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
576
- * // => { A: "bar", B: "xbary" }
577
- * ```
756
+ * Converts programmatic CLI options to `getDotenv` options. *
757
+ * @param cliOptions - CLI options. Defaults to `{}`.
578
758
  *
579
- * @remarks
580
- * Options:
581
- * - ref: The reference object to use for expansion (defaults to process.env).
582
- * - progressive: Whether to progressively add expanded values to the set of
583
- * reference keys.
759
+ * @returns `getDotenv` options.
760
+ */
761
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
762
+ /**
763
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
764
+ *
765
+ * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
766
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
767
+ * - Drops CLI-only keys that have no programmatic equivalent.
768
+ *
769
+ * @remarks
770
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
771
+ */
772
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
773
+ // Create a shallow copy then delete optional CLI-only keys if present.
774
+ const restObj = { ...rest };
775
+ delete restObj.debug;
776
+ delete restObj.scripts;
777
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
778
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
779
+ let parsedVars;
780
+ if (typeof vars === 'string') {
781
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
782
+ ? RegExp(varsAssignorPattern)
783
+ : (varsAssignor ?? '=')));
784
+ parsedVars = Object.fromEntries(kvPairs);
785
+ }
786
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
787
+ // Keep only string or undefined values to match ProcessEnv.
788
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
789
+ parsedVars = Object.fromEntries(entries);
790
+ }
791
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
792
+ // expectations and the compat test assertions.
793
+ if (parsedVars) {
794
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
795
+ }
796
+ // Tolerate paths as either a delimited string or string[]
797
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
798
+ // under the RootOptionsShape (which declares paths as string | undefined).
799
+ const pathsAny = paths;
800
+ const pathsOut = Array.isArray(pathsAny)
801
+ ? pathsAny.filter((p) => typeof p === 'string')
802
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
803
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
804
+ return {
805
+ ...restObj,
806
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
807
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
808
+ };
809
+ };
810
+ const resolveGetDotenvOptions = async (customOptions) => {
811
+ /**
812
+ * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
813
+ *
814
+ * 1. Base defaults derived from the CLI generator defaults
815
+ * ({@link baseGetDotenvCliOptions}).
816
+ * 2. Local project overrides from a `getdotenv.config.json` in the nearest
817
+ * package root (if present).
818
+ * 3. The provided {@link customOptions}.
819
+ *
820
+ * The result preserves explicit empty values and drops only `undefined`.
821
+ *
822
+ * @returns Fully-resolved {@link GetDotenvOptions}.
823
+ *
824
+ * @example
825
+ * ```ts
826
+ * const options = await resolveGetDotenvOptions({ env: 'dev' });
827
+ * ```
828
+ */
829
+ const localPkgDir = await packageDirectory();
830
+ const localOptionsPath = localPkgDir
831
+ ? join(localPkgDir, getDotenvOptionsFilename)
832
+ : undefined;
833
+ const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
834
+ ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
835
+ : {});
836
+ // Merge order: base < local < custom (custom has highest precedence)
837
+ const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
838
+ const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
839
+ const result = defaultsDeep(defaultsFromCli, customOptions);
840
+ return {
841
+ ...result, // Keep explicit empty strings/zeros; drop only undefined
842
+ vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
843
+ };
844
+ };
845
+
846
+ /**
847
+ * Zod schemas for programmatic GetDotenv options.
584
848
  *
585
- * When `progressive` is true, each expanded key becomes available for
586
- * subsequent expansions in the same object (left-to-right by object key order).
849
+ * NOTE: These schemas are introduced without wiring to avoid behavior changes.
850
+ * Legacy paths continue to use existing types/logic. The new plugin host will
851
+ * use these schemas in strict mode; legacy paths will adopt them in warn mode
852
+ * later per the staged plan.
587
853
  */
588
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
589
- const { ref = process.env, progressive = false } = options;
590
- acc[key] = dotenvExpand(values[key], {
591
- ...ref,
592
- ...(progressive ? acc : {}),
593
- });
594
- return acc;
595
- }, {});
854
+ // Minimal process env representation: string values or undefined to indicate "unset".
855
+ const processEnvSchema = z.record(z.string(), z.string().optional());
856
+ // RAW: all fields optional — undefined means "inherit" from lower layers.
857
+ const getDotenvOptionsSchemaRaw = z.object({
858
+ defaultEnv: z.string().optional(),
859
+ dotenvToken: z.string().optional(),
860
+ dynamicPath: z.string().optional(),
861
+ // Dynamic map is intentionally wide for now; refine once sources are normalized.
862
+ dynamic: z.record(z.string(), z.unknown()).optional(),
863
+ env: z.string().optional(),
864
+ excludeDynamic: z.boolean().optional(),
865
+ excludeEnv: z.boolean().optional(),
866
+ excludeGlobal: z.boolean().optional(),
867
+ excludePrivate: z.boolean().optional(),
868
+ excludePublic: z.boolean().optional(),
869
+ loadProcess: z.boolean().optional(),
870
+ log: z.boolean().optional(),
871
+ outputPath: z.string().optional(),
872
+ paths: z.array(z.string()).optional(),
873
+ privateToken: z.string().optional(),
874
+ vars: processEnvSchema.optional(),
875
+ // Host-only feature flag: guarded integration of config loader/overlay
876
+ useConfigLoader: z.boolean().optional(),
877
+ });
878
+ // RESOLVED: service-boundary contract (post-inheritance).
879
+ // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
880
+ const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
596
881
 
597
882
  const applyKv = (current, kv) => {
598
883
  if (!kv || Object.keys(kv).length === 0)
@@ -1185,7 +1470,7 @@ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1185
1470
  *
1186
1471
  * NOTE: This host is additive and does not alter the legacy CLI.
1187
1472
  */
1188
- class GetDotenvCli extends Command {
1473
+ let GetDotenvCli$1 = class GetDotenvCli extends Command {
1189
1474
  /** Registered top-level plugins (composition happens via .use()) */
1190
1475
  _plugins = [];
1191
1476
  /** One-time installation guard */
@@ -1441,8 +1726,130 @@ class GetDotenvCli extends Command {
1441
1726
  }
1442
1727
  return out;
1443
1728
  }
1444
- }
1729
+ };
1730
+
1731
+ /** src/cliHost/definePlugin.ts
1732
+ * Plugin contracts for the GetDotenv CLI host.
1733
+ *
1734
+ * This module exposes a structural public interface for the host that plugins
1735
+ * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
1736
+ * nominal class identity issues (private fields) in downstream consumers.
1737
+ */
1738
+ /**
1739
+ * Define a GetDotenv CLI plugin with compositional helpers.
1740
+ *
1741
+ * @example
1742
+ * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
1743
+ * .use(childA)
1744
+ * .use(childB);
1745
+ */
1746
+ const definePlugin = (spec) => {
1747
+ const { children = [], ...rest } = spec;
1748
+ const plugin = {
1749
+ ...rest,
1750
+ children: [...children],
1751
+ use(child) {
1752
+ this.children.push(child);
1753
+ return this;
1754
+ },
1755
+ };
1756
+ return plugin;
1757
+ };
1445
1758
 
1759
+ /**
1760
+ * GetDotenvCli with root helpers as real class methods.
1761
+ * - attachRootOptions: installs legacy/base root flags on the command.
1762
+ * - passOptions: merges flags (parent \< current), computes dotenv context once,
1763
+ * runs validation, and persists merged options for nested flows.
1764
+ */
1765
+ class GetDotenvCli extends GetDotenvCli$1 {
1766
+ /**
1767
+ * Attach legacy root flags to this CLI instance. Defaults come from
1768
+ * baseRootOptionDefaults when none are provided.
1769
+ */
1770
+ attachRootOptions(defaults, opts) {
1771
+ const d = (defaults ?? baseRootOptionDefaults);
1772
+ attachRootOptions(this, d, opts);
1773
+ return this;
1774
+ }
1775
+ /**
1776
+ * Install preSubcommand/preAction hooks that:
1777
+ * - Merge options (parent round-trip + current invocation) using resolveCliOptions.
1778
+ * - Persist the merged bag on the current command and on the host (for ergonomics).
1779
+ * - Compute the dotenv context once via resolveAndLoad(serviceOptions).
1780
+ * - Validate the composed env against discovered config (warn or --strict fail).
1781
+ */
1782
+ passOptions(defaults) {
1783
+ const d = (defaults ?? baseRootOptionDefaults);
1784
+ this.hook('preSubcommand', async (thisCommand) => {
1785
+ const raw = thisCommand.opts();
1786
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1787
+ // Persist merged options (for nested behavior and ergonomic access).
1788
+ thisCommand.getDotenvCliOptions =
1789
+ merged;
1790
+ this._setOptionsBag(merged);
1791
+ // Build service options and compute context (always-on loader path).
1792
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1793
+ await this.resolveAndLoad(serviceOptions);
1794
+ // Global validation: once after Phase C using config sources.
1795
+ try {
1796
+ const ctx = this.getCtx();
1797
+ const dotenv = (ctx?.dotenv ?? {});
1798
+ const sources = await resolveGetDotenvConfigSources(import.meta.url);
1799
+ const issues = validateEnvAgainstSources(dotenv, sources);
1800
+ if (Array.isArray(issues) && issues.length > 0) {
1801
+ const logger = (merged
1802
+ .logger ?? console);
1803
+ const emit = logger.error ?? logger.log;
1804
+ issues.forEach((m) => {
1805
+ emit(m);
1806
+ });
1807
+ if (merged.strict) {
1808
+ process.exit(1);
1809
+ }
1810
+ }
1811
+ }
1812
+ catch {
1813
+ // Be tolerant: do not crash non-strict flows on unexpected validator failures.
1814
+ }
1815
+ });
1816
+ // Also handle root-level flows (no subcommand) so option-aliases can run
1817
+ // with the same merged options and context without duplicating logic.
1818
+ this.hook('preAction', async (thisCommand) => {
1819
+ const raw = thisCommand.opts();
1820
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1821
+ thisCommand.getDotenvCliOptions =
1822
+ merged;
1823
+ this._setOptionsBag(merged);
1824
+ // Avoid duplicate heavy work if a context is already present.
1825
+ if (!this.getCtx()) {
1826
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1827
+ await this.resolveAndLoad(serviceOptions);
1828
+ try {
1829
+ const ctx = this.getCtx();
1830
+ const dotenv = (ctx?.dotenv ?? {});
1831
+ const sources = await resolveGetDotenvConfigSources(import.meta.url);
1832
+ const issues = validateEnvAgainstSources(dotenv, sources);
1833
+ if (Array.isArray(issues) && issues.length > 0) {
1834
+ const logger = (merged
1835
+ .logger ?? console);
1836
+ const emit = logger.error ?? logger.log;
1837
+ issues.forEach((m) => {
1838
+ emit(m);
1839
+ });
1840
+ if (merged.strict) {
1841
+ process.exit(1);
1842
+ }
1843
+ }
1844
+ }
1845
+ catch {
1846
+ // Tolerate validation side-effects in non-strict mode.
1847
+ }
1848
+ }
1849
+ });
1850
+ return this;
1851
+ }
1852
+ }
1446
1853
  /**
1447
1854
  * Helper to retrieve the merged root options bag from any action handler
1448
1855
  * that only has access to thisCommand. Avoids structural casts.