@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/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { Command, Option } 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';
@@ -13,6 +13,258 @@ import { globby } from 'globby';
13
13
  import { stdin, stdout } from 'node:process';
14
14
  import { createInterface } from 'readline/promises';
15
15
 
16
+ /**
17
+ * Dotenv expansion utilities.
18
+ *
19
+ * This module implements recursive expansion of environment-variable
20
+ * references in strings and records. It supports both whitespace and
21
+ * bracket syntaxes with optional defaults:
22
+ *
23
+ * - Whitespace: `$VAR[:default]`
24
+ * - Bracketed: `${VAR[:default]}`
25
+ *
26
+ * Escaped dollar signs (`\$`) are preserved.
27
+ * Unknown variables resolve to empty string unless a default is provided.
28
+ */
29
+ /**
30
+ * Like String.prototype.search but returns the last index.
31
+ * @internal
32
+ */
33
+ const searchLast = (str, rgx) => {
34
+ const matches = Array.from(str.matchAll(rgx));
35
+ return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
36
+ };
37
+ const replaceMatch = (value, match, ref) => {
38
+ /**
39
+ * @internal
40
+ */
41
+ const group = match[0];
42
+ const key = match[1];
43
+ const defaultValue = match[2];
44
+ if (!key)
45
+ return value;
46
+ const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
47
+ return interpolate(replacement, ref);
48
+ };
49
+ const interpolate = (value = '', ref = {}) => {
50
+ /**
51
+ * @internal
52
+ */
53
+ // if value is falsy, return it as is
54
+ if (!value)
55
+ return value;
56
+ // get position of last unescaped dollar sign
57
+ const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
58
+ // return value if none found
59
+ if (lastUnescapedDollarSignIndex === -1)
60
+ return value;
61
+ // evaluate the value tail
62
+ const tail = value.slice(lastUnescapedDollarSignIndex);
63
+ // find whitespace pattern: $KEY:DEFAULT
64
+ const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
65
+ const whitespaceMatch = whitespacePattern.exec(tail);
66
+ if (whitespaceMatch != null)
67
+ return replaceMatch(value, whitespaceMatch, ref);
68
+ else {
69
+ // find bracket pattern: ${KEY:DEFAULT}
70
+ const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
71
+ const bracketMatch = bracketPattern.exec(tail);
72
+ if (bracketMatch != null)
73
+ return replaceMatch(value, bracketMatch, ref);
74
+ }
75
+ return value;
76
+ };
77
+ /**
78
+ * Recursively expands environment variables in a string. Variables may be
79
+ * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
80
+ * Unknown variables will expand to an empty string.
81
+ *
82
+ * @param value - The string to expand.
83
+ * @param ref - The reference object to use for variable expansion.
84
+ * @returns The expanded string.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * process.env.FOO = 'bar';
89
+ * dotenvExpand('Hello $FOO'); // "Hello bar"
90
+ * dotenvExpand('Hello $BAZ:world'); // "Hello world"
91
+ * ```
92
+ *
93
+ * @remarks
94
+ * The expansion is recursive. If a referenced variable itself contains
95
+ * references, those will also be expanded until a stable value is reached.
96
+ * Escaped references (e.g. `\$FOO`) are preserved as literals.
97
+ */
98
+ const dotenvExpand = (value, ref = process.env) => {
99
+ const result = interpolate(value, ref);
100
+ return result ? result.replace(/\\\$/g, '$') : undefined;
101
+ };
102
+ /**
103
+ * Recursively expands environment variables in the values of a JSON object.
104
+ * Variables may be presented with optional default as `$VAR[:default]` or
105
+ * `${VAR[:default]}`. Unknown variables will expand to an empty string.
106
+ *
107
+ * @param values - The values object to expand.
108
+ * @param options - Expansion options.
109
+ * @returns The value object with expanded string values.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * process.env.FOO = 'bar';
114
+ * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
115
+ * // => { A: "bar", B: "xbary" }
116
+ * ```
117
+ *
118
+ * @remarks
119
+ * Options:
120
+ * - ref: The reference object to use for expansion (defaults to process.env).
121
+ * - progressive: Whether to progressively add expanded values to the set of
122
+ * reference keys.
123
+ *
124
+ * When `progressive` is true, each expanded key becomes available for
125
+ * subsequent expansions in the same object (left-to-right by object key order).
126
+ */
127
+ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
128
+ const { ref = process.env, progressive = false } = options;
129
+ acc[key] = dotenvExpand(values[key], {
130
+ ...ref,
131
+ ...(progressive ? acc : {}),
132
+ });
133
+ return acc;
134
+ }, {});
135
+ /**
136
+ * Recursively expands environment variables in a string using `process.env` as
137
+ * the expansion reference. Variables may be presented with optional default as
138
+ * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
139
+ * empty string.
140
+ *
141
+ * @param value - The string to expand.
142
+ * @returns The expanded string.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * process.env.FOO = 'bar';
147
+ * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
148
+ * ```
149
+ */
150
+ const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
151
+
152
+ /**
153
+ * Attach legacy root flags to a Commander program.
154
+ * Uses provided defaults to render help labels without coupling to generators.
155
+ */
156
+ const attachRootOptions = (program, defaults, opts) => {
157
+ // Install temporary wrappers to tag all options added here as "base".
158
+ const GROUP = 'base';
159
+ const tagLatest = (cmd, group) => {
160
+ const optsArr = cmd.options;
161
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
162
+ const last = optsArr[optsArr.length - 1];
163
+ last.__group = group;
164
+ }
165
+ };
166
+ const originalAddOption = program.addOption.bind(program);
167
+ const originalOption = program.option.bind(program);
168
+ program.addOption = function patchedAdd(opt) {
169
+ // Tag before adding, in case consumers inspect the Option directly.
170
+ opt.__group = GROUP;
171
+ const ret = originalAddOption(opt);
172
+ return ret;
173
+ };
174
+ program.option = function patchedOption(...args) {
175
+ const ret = originalOption(...args);
176
+ tagLatest(this, GROUP);
177
+ return ret;
178
+ };
179
+ const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
180
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
181
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
182
+ // Build initial chain.
183
+ let p = program
184
+ .enablePositionalOptions()
185
+ .passThroughOptions()
186
+ .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
187
+ p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
188
+ ['KEY1', 'VAL1'],
189
+ ['KEY2', 'VAL2'],
190
+ ]
191
+ .map((v) => v.join(va))
192
+ .join(vd)}`, dotenvExpandFromProcessEnv);
193
+ // Optional legacy root command flag (kept for generated CLI compatibility).
194
+ // Default is OFF; the generator opts in explicitly.
195
+ if (opts?.includeCommandOption === true) {
196
+ p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
197
+ }
198
+ p = p
199
+ .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
200
+ .addOption(new Option('-s, --shell [string]', (() => {
201
+ let defaultLabel = '';
202
+ if (shell !== undefined) {
203
+ if (typeof shell === 'boolean') {
204
+ defaultLabel = ' (default OS shell)';
205
+ }
206
+ else if (typeof shell === 'string') {
207
+ // Safe string interpolation
208
+ defaultLabel = ` (default ${shell})`;
209
+ }
210
+ }
211
+ return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
212
+ })()).conflicts('shellOff'))
213
+ .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
214
+ .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
215
+ .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
216
+ .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
217
+ ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
218
+ ? ' (default)'
219
+ : ''}`).conflicts('excludeAllOff'))
220
+ .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
221
+ .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
222
+ .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
223
+ .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
224
+ .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
225
+ .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
226
+ .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
227
+ .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
228
+ .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
229
+ .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
230
+ .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
231
+ .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
232
+ .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
233
+ .option('--capture', 'capture child process stdio for commands (tests/CI)')
234
+ .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
235
+ .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
236
+ .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
237
+ .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
238
+ .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
239
+ .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
240
+ .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
241
+ .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
242
+ .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
243
+ .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
244
+ .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
245
+ .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
246
+ // Hidden scripts pipe-through (stringified)
247
+ .addOption(new Option('--scripts <string>')
248
+ .default(JSON.stringify(scripts))
249
+ .hideHelp());
250
+ // Diagnostics: opt-in tracing; optional variadic keys after the flag.
251
+ p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
252
+ // Validation: strict mode fails on env validation issues (warn by default).
253
+ p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
254
+ // Entropy diagnostics (presentation-only)
255
+ p = p
256
+ .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
257
+ .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
258
+ .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
259
+ .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
260
+ .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
261
+ .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
262
+ // Restore original methods to avoid tagging future additions outside base.
263
+ program.addOption = originalAddOption;
264
+ program.option = originalOption;
265
+ return p;
266
+ };
267
+
16
268
  // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
17
269
  const baseRootOptionDefaults = {
18
270
  dotenvToken: '.env',
@@ -40,8 +292,6 @@ const baseRootOptionDefaults = {
40
292
  // (debug/log/exclude* resolved via flag utils)
41
293
  };
42
294
 
43
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
44
-
45
295
  /** @internal */
46
296
  const isPlainObject$1 = (value) => value !== null &&
47
297
  typeof value === 'object' &&
@@ -84,141 +334,130 @@ const defaultsDeep = (...layers) => {
84
334
  return result;
85
335
  };
86
336
 
87
- // src/GetDotenvOptions.ts
88
- const getDotenvOptionsFilename = 'getdotenv.config.json';
89
337
  /**
90
- * Helper to define a dynamic map with strong inference.
338
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
339
+ * - If the user explicitly enabled the flag, return true.
340
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
341
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
342
+ *
343
+ * @param exclude - The "on" flag value as parsed by Commander.
344
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
345
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
346
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
91
347
  *
92
348
  * @example
93
- * const dynamic = defineDynamic(\{ KEY: (\{ FOO = '' \}) =\> FOO + '-x' \});
349
+ * ```ts
350
+ * resolveExclusion(undefined, undefined, true); // => true
351
+ * ```
94
352
  */
95
- const defineDynamic = (d) => d;
353
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
96
354
  /**
97
- * Converts programmatic CLI options to `getDotenv` options. *
98
- * @param cliOptions - CLI options. Defaults to `{}`.
355
+ * Resolve an optional flag with "--exclude-all" overrides.
356
+ * If excludeAll is set and the individual "...-off" is not, force true.
357
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
358
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
99
359
  *
100
- * @returns `getDotenv` options.
360
+ * @param exclude - Individual include/exclude flag.
361
+ * @param excludeOff - Individual "...-off" flag.
362
+ * @param defaultValue - Default for the individual flag.
363
+ * @param excludeAll - Global "exclude-all" flag.
364
+ * @param excludeAllOff - Global "exclude-all-off" flag.
365
+ *
366
+ * @example
367
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
101
368
  */
102
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
103
- /**
104
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
105
- *
106
- * - 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`
107
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
108
- * - Drops CLI-only keys that have no programmatic equivalent.
109
- *
110
- * @remarks
111
- * Follows exact-optional semantics by not emitting undefined-valued entries.
112
- */
113
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
114
- // Create a shallow copy then delete optional CLI-only keys if present.
115
- const restObj = { ...rest };
116
- delete restObj.debug;
117
- delete restObj.scripts;
118
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
119
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
120
- let parsedVars;
121
- if (typeof vars === 'string') {
122
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
123
- ? RegExp(varsAssignorPattern)
124
- : (varsAssignor ?? '=')));
125
- parsedVars = Object.fromEntries(kvPairs);
126
- }
127
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
128
- // Keep only string or undefined values to match ProcessEnv.
129
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
130
- parsedVars = Object.fromEntries(entries);
131
- }
132
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
133
- // expectations and the compat test assertions.
134
- if (parsedVars) {
135
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
136
- }
137
- // Tolerate paths as either a delimited string or string[]
138
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
139
- // under the RootOptionsShape (which declares paths as string | undefined).
140
- const pathsAny = paths;
141
- const pathsOut = Array.isArray(pathsAny)
142
- ? pathsAny.filter((p) => typeof p === 'string')
143
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
144
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
145
- return {
146
- ...restObj,
147
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
148
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
149
- };
150
- };
151
- const resolveGetDotenvOptions = async (customOptions) => {
152
- /**
153
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
154
- *
155
- * 1. Base defaults derived from the CLI generator defaults
156
- * ({@link baseGetDotenvCliOptions}).
157
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
158
- * package root (if present).
159
- * 3. The provided {@link customOptions}.
160
- *
161
- * The result preserves explicit empty values and drops only `undefined`.
162
- *
163
- * @returns Fully-resolved {@link GetDotenvOptions}.
164
- *
165
- * @example
166
- * ```ts
167
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
168
- * ```
169
- */
170
- const localPkgDir = await packageDirectory();
171
- const localOptionsPath = localPkgDir
172
- ? join(localPkgDir, getDotenvOptionsFilename)
173
- : undefined;
174
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
175
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
176
- : {});
177
- // Merge order: base < local < custom (custom has highest precedence)
178
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
179
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
180
- const result = defaultsDeep(defaultsFromCli, customOptions);
181
- return {
182
- ...result, // Keep explicit empty strings/zeros; drop only undefined
183
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
184
- };
369
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
370
+ // Order of precedence:
371
+ // 1) Individual explicit "on" wins outright.
372
+ // 2) Individual explicit "off" wins over any global.
373
+ // 3) Global exclude-all forces true when not explicitly turned off.
374
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
375
+ // 5) Fall back to the default (true => set; false/undefined => unset).
376
+ (() => {
377
+ // Individual "on"
378
+ if (exclude === true)
379
+ return true;
380
+ // Individual "off"
381
+ if (excludeOff === true)
382
+ return undefined;
383
+ // Global "exclude-all" ON (unless explicitly turned off)
384
+ if (excludeAll === true)
385
+ return true;
386
+ // Global "exclude-all-off" (unless explicitly enabled)
387
+ if (excludeAllOff === true)
388
+ return undefined;
389
+ // Default
390
+ return defaultValue ? true : undefined;
391
+ })();
392
+ /**
393
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
394
+ * delete when undefined; assign when defined without requiring an index signature on T.
395
+ *
396
+ * @typeParam T - Target object type.
397
+ * @param obj - The object to write to.
398
+ * @param key - The optional boolean property key of {@link T}.
399
+ * @param value - The value to set or `undefined` to unset.
400
+ *
401
+ * @remarks
402
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
403
+ */
404
+ const setOptionalFlag = (obj, key, value) => {
405
+ const target = obj;
406
+ const k = key;
407
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
408
+ if (value === undefined)
409
+ delete target[k];
410
+ else
411
+ target[k] = value;
185
412
  };
186
413
 
187
414
  /**
188
- * Zod schemas for programmatic GetDotenv options.
189
- *
190
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
191
- * Legacy paths continue to use existing types/logic. The new plugin host will
192
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
193
- * later per the staged plan.
415
+ * Merge and normalize raw Commander options (current + parent + defaults)
416
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
417
+ * avoid cross-layer coupling; callers may cast as needed.
194
418
  */
195
- // Minimal process env representation: string values or undefined to indicate "unset".
196
- const processEnvSchema = z.record(z.string(), z.string().optional());
197
- // RAW: all fields optional — undefined means "inherit" from lower layers.
198
- const getDotenvOptionsSchemaRaw = z.object({
199
- defaultEnv: z.string().optional(),
200
- dotenvToken: z.string().optional(),
201
- dynamicPath: z.string().optional(),
202
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
203
- dynamic: z.record(z.string(), z.unknown()).optional(),
204
- env: z.string().optional(),
205
- excludeDynamic: z.boolean().optional(),
206
- excludeEnv: z.boolean().optional(),
207
- excludeGlobal: z.boolean().optional(),
208
- excludePrivate: z.boolean().optional(),
209
- excludePublic: z.boolean().optional(),
210
- loadProcess: z.boolean().optional(),
211
- log: z.boolean().optional(),
212
- outputPath: z.string().optional(),
213
- paths: z.array(z.string()).optional(),
214
- privateToken: z.string().optional(),
215
- vars: processEnvSchema.optional(),
216
- // Host-only feature flag: guarded integration of config loader/overlay
217
- useConfigLoader: z.boolean().optional(),
218
- });
219
- // RESOLVED: service-boundary contract (post-inheritance).
220
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
221
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
419
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
420
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
421
+ ? JSON.parse(parentJson)
422
+ : undefined;
423
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
424
+ const current = { ...rest };
425
+ if (typeof scripts === 'string') {
426
+ try {
427
+ current.scripts = JSON.parse(scripts);
428
+ }
429
+ catch {
430
+ // ignore parse errors; leave scripts undefined
431
+ }
432
+ }
433
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
434
+ const d = defaults;
435
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
436
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
437
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
438
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
439
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
440
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
441
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
442
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
443
+ // warnEntropy (tri-state)
444
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
445
+ // Normalize shell for predictability: explicit default shell per OS.
446
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
447
+ let resolvedShell = merged.shell;
448
+ if (shellOff)
449
+ resolvedShell = false;
450
+ else if (resolvedShell === true || resolvedShell === undefined) {
451
+ resolvedShell = defaultShell;
452
+ }
453
+ else if (typeof resolvedShell !== 'string' &&
454
+ typeof defaults.shell === 'string') {
455
+ resolvedShell = defaults.shell;
456
+ }
457
+ merged.shell = resolvedShell;
458
+ const cmd = typeof command === 'string' ? command : undefined;
459
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
460
+ };
222
461
 
223
462
  /**
224
463
  * Zod schemas for configuration files discovered by the new loader.
@@ -458,140 +697,198 @@ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
458
697
  };
459
698
 
460
699
  /**
461
- * Dotenv expansion utilities.
462
- *
463
- * This module implements recursive expansion of environment-variable
464
- * references in strings and records. It supports both whitespace and
465
- * bracket syntaxes with optional defaults:
466
- *
467
- * - Whitespace: `$VAR[:default]`
468
- * - Bracketed: `${VAR[:default]}`
700
+ * Validate a composed env against config-provided validation surfaces.
701
+ * Precedence for validation definitions:
702
+ * project.local -\> project.public -\> packaged
469
703
  *
470
- * Escaped dollar signs (`\$`) are preserved.
471
- * Unknown variables resolve to empty string unless a default is provided.
472
- */
473
- /**
474
- * Like String.prototype.search but returns the last index.
475
- * @internal
704
+ * Behavior:
705
+ * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
706
+ * - Else if `requiredKeys` is present, check presence (value !== undefined).
707
+ * - Returns a flat list of issue strings; caller decides warn vs fail.
476
708
  */
477
- const searchLast = (str, rgx) => {
478
- const matches = Array.from(str.matchAll(rgx));
479
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
480
- };
481
- const replaceMatch = (value, match, ref) => {
482
- /**
483
- * @internal
484
- */
485
- const group = match[0];
486
- const key = match[1];
487
- const defaultValue = match[2];
488
- if (!key)
489
- return value;
490
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
491
- return interpolate(replacement, ref);
492
- };
493
- const interpolate = (value = '', ref = {}) => {
494
- /**
495
- * @internal
496
- */
497
- // if value is falsy, return it as is
498
- if (!value)
499
- return value;
500
- // get position of last unescaped dollar sign
501
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
502
- // return value if none found
503
- if (lastUnescapedDollarSignIndex === -1)
504
- return value;
505
- // evaluate the value tail
506
- const tail = value.slice(lastUnescapedDollarSignIndex);
507
- // find whitespace pattern: $KEY:DEFAULT
508
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
509
- const whitespaceMatch = whitespacePattern.exec(tail);
510
- if (whitespaceMatch != null)
511
- return replaceMatch(value, whitespaceMatch, ref);
512
- else {
513
- // find bracket pattern: ${KEY:DEFAULT}
514
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
515
- const bracketMatch = bracketPattern.exec(tail);
516
- if (bracketMatch != null)
517
- return replaceMatch(value, bracketMatch, ref);
709
+ const validateEnvAgainstSources = (finalEnv, sources) => {
710
+ const pick = (getter) => {
711
+ const pl = sources.project?.local;
712
+ const pp = sources.project?.public;
713
+ const pk = sources.packaged;
714
+ return ((pl && getter(pl)) ||
715
+ (pp && getter(pp)) ||
716
+ (pk && getter(pk)) ||
717
+ undefined);
718
+ };
719
+ const schema = pick((cfg) => cfg['schema']);
720
+ if (schema &&
721
+ typeof schema.safeParse === 'function') {
722
+ try {
723
+ const parsed = schema.safeParse(finalEnv);
724
+ if (!parsed.success) {
725
+ // Try to render zod-style issues when available.
726
+ const err = parsed.error;
727
+ const issues = Array.isArray(err.issues) && err.issues.length > 0
728
+ ? err.issues.map((i) => {
729
+ const path = Array.isArray(i.path) ? i.path.join('.') : '';
730
+ const msg = i.message ?? 'Invalid value';
731
+ return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
732
+ })
733
+ : ['[schema] validation failed'];
734
+ return issues;
735
+ }
736
+ return [];
737
+ }
738
+ catch {
739
+ // If schema invocation fails, surface a single diagnostic.
740
+ return [
741
+ '[schema] validation failed (unable to execute schema.safeParse)',
742
+ ];
743
+ }
518
744
  }
519
- return value;
745
+ const requiredKeys = pick((cfg) => cfg['requiredKeys']);
746
+ if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
747
+ const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
748
+ if (missing.length > 0) {
749
+ return missing.map((k) => `[requiredKeys] missing: ${k}`);
750
+ }
751
+ }
752
+ return [];
520
753
  };
754
+
755
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
756
+
757
+ // src/GetDotenvOptions.ts
758
+ const getDotenvOptionsFilename = 'getdotenv.config.json';
521
759
  /**
522
- * Recursively expands environment variables in a string. Variables may be
523
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
524
- * Unknown variables will expand to an empty string.
525
- *
526
- * @param value - The string to expand.
527
- * @param ref - The reference object to use for variable expansion.
528
- * @returns The expanded string.
760
+ * Helper to define a dynamic map with strong inference.
529
761
  *
530
762
  * @example
531
- * ```ts
532
- * process.env.FOO = 'bar';
533
- * dotenvExpand('Hello $FOO'); // "Hello bar"
534
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
535
- * ```
536
- *
537
- * @remarks
538
- * The expansion is recursive. If a referenced variable itself contains
539
- * references, those will also be expanded until a stable value is reached.
540
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
763
+ * const dynamic = defineDynamic(\{ KEY: (\{ FOO = '' \}) =\> FOO + '-x' \});
541
764
  */
542
- const dotenvExpand = (value, ref = process.env) => {
543
- const result = interpolate(value, ref);
544
- return result ? result.replace(/\\\$/g, '$') : undefined;
545
- };
765
+ const defineDynamic = (d) => d;
546
766
  /**
547
- * Recursively expands environment variables in the values of a JSON object.
548
- * Variables may be presented with optional default as `$VAR[:default]` or
549
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
550
- *
551
- * @param values - The values object to expand.
552
- * @param options - Expansion options.
553
- * @returns The value object with expanded string values.
554
- *
555
- * @example
556
- * ```ts
557
- * process.env.FOO = 'bar';
558
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
559
- * // => { A: "bar", B: "xbary" }
560
- * ```
561
- *
562
- * @remarks
563
- * Options:
564
- * - ref: The reference object to use for expansion (defaults to process.env).
565
- * - progressive: Whether to progressively add expanded values to the set of
566
- * reference keys.
767
+ * Converts programmatic CLI options to `getDotenv` options. *
768
+ * @param cliOptions - CLI options. Defaults to `{}`.
567
769
  *
568
- * When `progressive` is true, each expanded key becomes available for
569
- * subsequent expansions in the same object (left-to-right by object key order).
770
+ * @returns `getDotenv` options.
570
771
  */
571
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
572
- const { ref = process.env, progressive = false } = options;
573
- acc[key] = dotenvExpand(values[key], {
574
- ...ref,
575
- ...(progressive ? acc : {}),
576
- });
577
- return acc;
578
- }, {});
772
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
773
+ /**
774
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
775
+ *
776
+ * - 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`
777
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
778
+ * - Drops CLI-only keys that have no programmatic equivalent.
779
+ *
780
+ * @remarks
781
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
782
+ */
783
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
784
+ // Create a shallow copy then delete optional CLI-only keys if present.
785
+ const restObj = { ...rest };
786
+ delete restObj.debug;
787
+ delete restObj.scripts;
788
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
789
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
790
+ let parsedVars;
791
+ if (typeof vars === 'string') {
792
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
793
+ ? RegExp(varsAssignorPattern)
794
+ : (varsAssignor ?? '=')));
795
+ parsedVars = Object.fromEntries(kvPairs);
796
+ }
797
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
798
+ // Keep only string or undefined values to match ProcessEnv.
799
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
800
+ parsedVars = Object.fromEntries(entries);
801
+ }
802
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
803
+ // expectations and the compat test assertions.
804
+ if (parsedVars) {
805
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
806
+ }
807
+ // Tolerate paths as either a delimited string or string[]
808
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
809
+ // under the RootOptionsShape (which declares paths as string | undefined).
810
+ const pathsAny = paths;
811
+ const pathsOut = Array.isArray(pathsAny)
812
+ ? pathsAny.filter((p) => typeof p === 'string')
813
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
814
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
815
+ return {
816
+ ...restObj,
817
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
818
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
819
+ };
820
+ };
821
+ const resolveGetDotenvOptions = async (customOptions) => {
822
+ /**
823
+ * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
824
+ *
825
+ * 1. Base defaults derived from the CLI generator defaults
826
+ * ({@link baseGetDotenvCliOptions}).
827
+ * 2. Local project overrides from a `getdotenv.config.json` in the nearest
828
+ * package root (if present).
829
+ * 3. The provided {@link customOptions}.
830
+ *
831
+ * The result preserves explicit empty values and drops only `undefined`.
832
+ *
833
+ * @returns Fully-resolved {@link GetDotenvOptions}.
834
+ *
835
+ * @example
836
+ * ```ts
837
+ * const options = await resolveGetDotenvOptions({ env: 'dev' });
838
+ * ```
839
+ */
840
+ const localPkgDir = await packageDirectory();
841
+ const localOptionsPath = localPkgDir
842
+ ? join(localPkgDir, getDotenvOptionsFilename)
843
+ : undefined;
844
+ const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
845
+ ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
846
+ : {});
847
+ // Merge order: base < local < custom (custom has highest precedence)
848
+ const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
849
+ const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
850
+ const result = defaultsDeep(defaultsFromCli, customOptions);
851
+ return {
852
+ ...result, // Keep explicit empty strings/zeros; drop only undefined
853
+ vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
854
+ };
855
+ };
856
+
579
857
  /**
580
- * Recursively expands environment variables in a string using `process.env` as
581
- * the expansion reference. Variables may be presented with optional default as
582
- * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
583
- * empty string.
584
- *
585
- * @param value - The string to expand.
586
- * @returns The expanded string.
858
+ * Zod schemas for programmatic GetDotenv options.
587
859
  *
588
- * @example
589
- * ```ts
590
- * process.env.FOO = 'bar';
591
- * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
592
- * ```
860
+ * NOTE: These schemas are introduced without wiring to avoid behavior changes.
861
+ * Legacy paths continue to use existing types/logic. The new plugin host will
862
+ * use these schemas in strict mode; legacy paths will adopt them in warn mode
863
+ * later per the staged plan.
593
864
  */
594
- const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
865
+ // Minimal process env representation: string values or undefined to indicate "unset".
866
+ const processEnvSchema = z.record(z.string(), z.string().optional());
867
+ // RAW: all fields optional — undefined means "inherit" from lower layers.
868
+ const getDotenvOptionsSchemaRaw = z.object({
869
+ defaultEnv: z.string().optional(),
870
+ dotenvToken: z.string().optional(),
871
+ dynamicPath: z.string().optional(),
872
+ // Dynamic map is intentionally wide for now; refine once sources are normalized.
873
+ dynamic: z.record(z.string(), z.unknown()).optional(),
874
+ env: z.string().optional(),
875
+ excludeDynamic: z.boolean().optional(),
876
+ excludeEnv: z.boolean().optional(),
877
+ excludeGlobal: z.boolean().optional(),
878
+ excludePrivate: z.boolean().optional(),
879
+ excludePublic: z.boolean().optional(),
880
+ loadProcess: z.boolean().optional(),
881
+ log: z.boolean().optional(),
882
+ outputPath: z.string().optional(),
883
+ paths: z.array(z.string()).optional(),
884
+ privateToken: z.string().optional(),
885
+ vars: processEnvSchema.optional(),
886
+ // Host-only feature flag: guarded integration of config loader/overlay
887
+ useConfigLoader: z.boolean().optional(),
888
+ });
889
+ // RESOLVED: service-boundary contract (post-inheritance).
890
+ // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
891
+ const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
595
892
 
596
893
  const applyKv = (current, kv) => {
597
894
  if (!kv || Object.keys(kv).length === 0)
@@ -1205,7 +1502,7 @@ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1205
1502
  *
1206
1503
  * NOTE: This host is additive and does not alter the legacy CLI.
1207
1504
  */
1208
- class GetDotenvCli extends Command {
1505
+ let GetDotenvCli$1 = class GetDotenvCli extends Command {
1209
1506
  /** Registered top-level plugins (composition happens via .use()) */
1210
1507
  _plugins = [];
1211
1508
  /** One-time installation guard */
@@ -1405,415 +1702,128 @@ class GetDotenvCli extends Command {
1405
1702
  await p.afterResolve(this, ctx);
1406
1703
  for (const child of p.children)
1407
1704
  await run(child);
1408
- };
1409
- for (const p of this._plugins)
1410
- await run(p);
1411
- }
1412
- // Render App/Plugin grouped options appended after default help.
1413
- #renderOptionGroups(cmd) {
1414
- const all = cmd.options ?? [];
1415
- const byGroup = new Map();
1416
- for (const o of all) {
1417
- const opt = o;
1418
- const g = opt.__group;
1419
- if (!g || g === 'base')
1420
- continue; // base handled by default help
1421
- const rows = byGroup.get(g) ?? [];
1422
- rows.push({
1423
- flags: opt.flags ?? '',
1424
- description: opt.description ?? '',
1425
- });
1426
- byGroup.set(g, rows);
1427
- }
1428
- if (byGroup.size === 0)
1429
- return '';
1430
- const renderRows = (title, rows) => {
1431
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1432
- // Sort within group: short-aliased flags first
1433
- rows.sort((a, b) => {
1434
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1435
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1436
- return bS - aS || a.flags.localeCompare(b.flags);
1437
- });
1438
- const lines = rows
1439
- .map((r) => {
1440
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1441
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1442
- })
1443
- .join('\n');
1444
- return `\n${title}:\n${lines}\n`;
1445
- };
1446
- let out = '';
1447
- // App options (if any)
1448
- const app = byGroup.get('app');
1449
- if (app && app.length > 0) {
1450
- out += renderRows('App options', app);
1451
- }
1452
- // Plugin groups sorted by id
1453
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1454
- pluginKeys.sort((a, b) => a.localeCompare(b));
1455
- for (const k of pluginKeys) {
1456
- const id = k.slice('plugin:'.length) || '(unknown)';
1457
- const rows = byGroup.get(k) ?? [];
1458
- if (rows.length > 0) {
1459
- out += renderRows(`Plugin options — ${id}`, rows);
1460
- }
1461
- }
1462
- return out;
1463
- }
1464
- }
1465
-
1466
- /**
1467
- * Validate a composed env against config-provided validation surfaces.
1468
- * Precedence for validation definitions:
1469
- * project.local -\> project.public -\> packaged
1470
- *
1471
- * Behavior:
1472
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
1473
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
1474
- * - Returns a flat list of issue strings; caller decides warn vs fail.
1475
- */
1476
- const validateEnvAgainstSources = (finalEnv, sources) => {
1477
- const pick = (getter) => {
1478
- const pl = sources.project?.local;
1479
- const pp = sources.project?.public;
1480
- const pk = sources.packaged;
1481
- return ((pl && getter(pl)) ||
1482
- (pp && getter(pp)) ||
1483
- (pk && getter(pk)) ||
1484
- undefined);
1485
- };
1486
- const schema = pick((cfg) => cfg['schema']);
1487
- if (schema &&
1488
- typeof schema.safeParse === 'function') {
1489
- try {
1490
- const parsed = schema.safeParse(finalEnv);
1491
- if (!parsed.success) {
1492
- // Try to render zod-style issues when available.
1493
- const err = parsed.error;
1494
- const issues = Array.isArray(err.issues) && err.issues.length > 0
1495
- ? err.issues.map((i) => {
1496
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
1497
- const msg = i.message ?? 'Invalid value';
1498
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
1499
- })
1500
- : ['[schema] validation failed'];
1501
- return issues;
1502
- }
1503
- return [];
1504
- }
1505
- catch {
1506
- // If schema invocation fails, surface a single diagnostic.
1507
- return [
1508
- '[schema] validation failed (unable to execute schema.safeParse)',
1509
- ];
1510
- }
1511
- }
1512
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
1513
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
1514
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
1515
- if (missing.length > 0) {
1516
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
1517
- }
1518
- }
1519
- return [];
1520
- };
1521
-
1522
- /**
1523
- * Attach legacy root flags to a Commander program.
1524
- * Uses provided defaults to render help labels without coupling to generators.
1525
- */
1526
- const attachRootOptions = (program, defaults, opts) => {
1527
- // Install temporary wrappers to tag all options added here as "base".
1528
- const GROUP = 'base';
1529
- const tagLatest = (cmd, group) => {
1530
- const optsArr = cmd.options;
1531
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1532
- const last = optsArr[optsArr.length - 1];
1533
- last.__group = group;
1534
- }
1535
- };
1536
- const originalAddOption = program.addOption.bind(program);
1537
- const originalOption = program.option.bind(program);
1538
- program.addOption = function patchedAdd(opt) {
1539
- // Tag before adding, in case consumers inspect the Option directly.
1540
- opt.__group = GROUP;
1541
- const ret = originalAddOption(opt);
1542
- return ret;
1543
- };
1544
- program.option = function patchedOption(...args) {
1545
- const ret = originalOption(...args);
1546
- tagLatest(this, GROUP);
1547
- return ret;
1548
- };
1549
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1550
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1551
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1552
- // Build initial chain.
1553
- let p = program
1554
- .enablePositionalOptions()
1555
- .passThroughOptions()
1556
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1557
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1558
- ['KEY1', 'VAL1'],
1559
- ['KEY2', 'VAL2'],
1560
- ]
1561
- .map((v) => v.join(va))
1562
- .join(vd)}`, dotenvExpandFromProcessEnv);
1563
- // Optional legacy root command flag (kept for generated CLI compatibility).
1564
- // Default is OFF; the generator opts in explicitly.
1565
- if (opts?.includeCommandOption === true) {
1566
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1567
- }
1568
- p = p
1569
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
1570
- .addOption(new Option('-s, --shell [string]', (() => {
1571
- let defaultLabel = '';
1572
- if (shell !== undefined) {
1573
- if (typeof shell === 'boolean') {
1574
- defaultLabel = ' (default OS shell)';
1575
- }
1576
- else if (typeof shell === 'string') {
1577
- // Safe string interpolation
1578
- defaultLabel = ` (default ${shell})`;
1579
- }
1580
- }
1581
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
1582
- })()).conflicts('shellOff'))
1583
- .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
1584
- .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
1585
- .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
1586
- .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1587
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1588
- ? ' (default)'
1589
- : ''}`).conflicts('excludeAllOff'))
1590
- .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
1591
- .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
1592
- .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
1593
- .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
1594
- .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
1595
- .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
1596
- .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
1597
- .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
1598
- .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
1599
- .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
1600
- .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
1601
- .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
1602
- .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
1603
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
1604
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
1605
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
1606
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
1607
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
1608
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
1609
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
1610
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
1611
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
1612
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
1613
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
1614
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
1615
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1616
- // Hidden scripts pipe-through (stringified)
1617
- .addOption(new Option('--scripts <string>')
1618
- .default(JSON.stringify(scripts))
1619
- .hideHelp());
1620
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1621
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1622
- // Validation: strict mode fails on env validation issues (warn by default).
1623
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1624
- // Entropy diagnostics (presentation-only)
1625
- p = p
1626
- .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
1627
- .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
1628
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
1629
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
1630
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
1631
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1632
- // Restore original methods to avoid tagging future additions outside base.
1633
- program.addOption = originalAddOption;
1634
- program.option = originalOption;
1635
- return p;
1705
+ };
1706
+ for (const p of this._plugins)
1707
+ await run(p);
1708
+ }
1709
+ // Render App/Plugin grouped options appended after default help.
1710
+ #renderOptionGroups(cmd) {
1711
+ const all = cmd.options ?? [];
1712
+ const byGroup = new Map();
1713
+ for (const o of all) {
1714
+ const opt = o;
1715
+ const g = opt.__group;
1716
+ if (!g || g === 'base')
1717
+ continue; // base handled by default help
1718
+ const rows = byGroup.get(g) ?? [];
1719
+ rows.push({
1720
+ flags: opt.flags ?? '',
1721
+ description: opt.description ?? '',
1722
+ });
1723
+ byGroup.set(g, rows);
1724
+ }
1725
+ if (byGroup.size === 0)
1726
+ return '';
1727
+ const renderRows = (title, rows) => {
1728
+ const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1729
+ // Sort within group: short-aliased flags first
1730
+ rows.sort((a, b) => {
1731
+ const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1732
+ const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1733
+ return bS - aS || a.flags.localeCompare(b.flags);
1734
+ });
1735
+ const lines = rows
1736
+ .map((r) => {
1737
+ const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1738
+ return ` ${r.flags}${pad}${r.description}`.trimEnd();
1739
+ })
1740
+ .join('\n');
1741
+ return `\n${title}:\n${lines}\n`;
1742
+ };
1743
+ let out = '';
1744
+ // App options (if any)
1745
+ const app = byGroup.get('app');
1746
+ if (app && app.length > 0) {
1747
+ out += renderRows('App options', app);
1748
+ }
1749
+ // Plugin groups sorted by id
1750
+ const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1751
+ pluginKeys.sort((a, b) => a.localeCompare(b));
1752
+ for (const k of pluginKeys) {
1753
+ const id = k.slice('plugin:'.length) || '(unknown)';
1754
+ const rows = byGroup.get(k) ?? [];
1755
+ if (rows.length > 0) {
1756
+ out += renderRows(`Plugin options — ${id}`, rows);
1757
+ }
1758
+ }
1759
+ return out;
1760
+ }
1636
1761
  };
1637
1762
 
1638
- /**
1639
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1640
- * - If the user explicitly enabled the flag, return true.
1641
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1642
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
1643
- *
1644
- * @param exclude - The "on" flag value as parsed by Commander.
1645
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1646
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1647
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1763
+ /** src/cliHost/definePlugin.ts
1764
+ * Plugin contracts for the GetDotenv CLI host.
1648
1765
  *
1649
- * @example
1650
- * ```ts
1651
- * resolveExclusion(undefined, undefined, true); // => true
1652
- * ```
1766
+ * This module exposes a structural public interface for the host that plugins
1767
+ * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
1768
+ * nominal class identity issues (private fields) in downstream consumers.
1653
1769
  */
1654
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1655
1770
  /**
1656
- * Resolve an optional flag with "--exclude-all" overrides.
1657
- * If excludeAll is set and the individual "...-off" is not, force true.
1658
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1659
- * Otherwise, adopt the default (true → set; false/undefined → unset).
1660
- *
1661
- * @param exclude - Individual include/exclude flag.
1662
- * @param excludeOff - Individual "...-off" flag.
1663
- * @param defaultValue - Default for the individual flag.
1664
- * @param excludeAll - Global "exclude-all" flag.
1665
- * @param excludeAllOff - Global "exclude-all-off" flag.
1771
+ * Define a GetDotenv CLI plugin with compositional helpers.
1666
1772
  *
1667
1773
  * @example
1668
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1669
- */
1670
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1671
- // Order of precedence:
1672
- // 1) Individual explicit "on" wins outright.
1673
- // 2) Individual explicit "off" wins over any global.
1674
- // 3) Global exclude-all forces true when not explicitly turned off.
1675
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1676
- // 5) Fall back to the default (true => set; false/undefined => unset).
1677
- (() => {
1678
- // Individual "on"
1679
- if (exclude === true)
1680
- return true;
1681
- // Individual "off"
1682
- if (excludeOff === true)
1683
- return undefined;
1684
- // Global "exclude-all" ON (unless explicitly turned off)
1685
- if (excludeAll === true)
1686
- return true;
1687
- // Global "exclude-all-off" (unless explicitly enabled)
1688
- if (excludeAllOff === true)
1689
- return undefined;
1690
- // Default
1691
- return defaultValue ? true : undefined;
1692
- })();
1693
- /**
1694
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1695
- * delete when undefined; assign when defined — without requiring an index signature on T.
1696
- *
1697
- * @typeParam T - Target object type.
1698
- * @param obj - The object to write to.
1699
- * @param key - The optional boolean property key of {@link T}.
1700
- * @param value - The value to set or `undefined` to unset.
1701
- *
1702
- * @remarks
1703
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1774
+ * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
1775
+ * .use(childA)
1776
+ * .use(childB);
1704
1777
  */
1705
- const setOptionalFlag = (obj, key, value) => {
1706
- const target = obj;
1707
- const k = key;
1708
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1709
- if (value === undefined)
1710
- delete target[k];
1711
- else
1712
- target[k] = value;
1778
+ const definePlugin = (spec) => {
1779
+ const { children = [], ...rest } = spec;
1780
+ const plugin = {
1781
+ ...rest,
1782
+ children: [...children],
1783
+ use(child) {
1784
+ this.children.push(child);
1785
+ return this;
1786
+ },
1787
+ };
1788
+ return plugin;
1713
1789
  };
1714
1790
 
1715
1791
  /**
1716
- * Merge and normalize raw Commander options (current + parent + defaults)
1717
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1718
- * avoid cross-layer coupling; callers may cast as needed.
1792
+ * GetDotenvCli with root helpers as real class methods.
1793
+ * - attachRootOptions: installs legacy/base root flags on the command.
1794
+ * - passOptions: merges flags (parent \< current), computes dotenv context once,
1795
+ * runs validation, and persists merged options for nested flows.
1719
1796
  */
1720
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1721
- const parent = typeof parentJson === 'string' && parentJson.length > 0
1722
- ? JSON.parse(parentJson)
1723
- : undefined;
1724
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1725
- const current = { ...rest };
1726
- if (typeof scripts === 'string') {
1727
- try {
1728
- current.scripts = JSON.parse(scripts);
1729
- }
1730
- catch {
1731
- // ignore parse errors; leave scripts undefined
1732
- }
1733
- }
1734
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1735
- const d = defaults;
1736
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1737
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1738
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1739
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1740
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1741
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1742
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1743
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1744
- // warnEntropy (tri-state)
1745
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1746
- // Normalize shell for predictability: explicit default shell per OS.
1747
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1748
- let resolvedShell = merged.shell;
1749
- if (shellOff)
1750
- resolvedShell = false;
1751
- else if (resolvedShell === true || resolvedShell === undefined) {
1752
- resolvedShell = defaultShell;
1753
- }
1754
- else if (typeof resolvedShell !== 'string' &&
1755
- typeof defaults.shell === 'string') {
1756
- resolvedShell = defaults.shell;
1797
+ class GetDotenvCli extends GetDotenvCli$1 {
1798
+ /**
1799
+ * Attach legacy root flags to this CLI instance. Defaults come from
1800
+ * baseRootOptionDefaults when none are provided.
1801
+ */
1802
+ attachRootOptions(defaults, opts) {
1803
+ const d = (defaults ?? baseRootOptionDefaults);
1804
+ attachRootOptions(this, d, opts);
1805
+ return this;
1757
1806
  }
1758
- merged.shell = resolvedShell;
1759
- const cmd = typeof command === 'string' ? command : undefined;
1760
- return cmd !== undefined ? { merged, command: cmd } : { merged };
1761
- };
1762
-
1763
- GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1764
- const d = (defaults ?? baseRootOptionDefaults);
1765
- attachRootOptions(this, d, opts);
1766
- return this;
1767
- };
1768
- GetDotenvCli.prototype.passOptions = function (defaults) {
1769
- const d = (defaults ?? baseRootOptionDefaults);
1770
- this.hook('preSubcommand', async (thisCommand) => {
1771
- const raw = thisCommand.opts();
1772
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1773
- // Persist merged options for nested invocations (batch exec).
1774
- thisCommand.getDotenvCliOptions =
1775
- merged;
1776
- // Also store on the host for downstream ergonomic accessors.
1777
- this._setOptionsBag(merged);
1778
- // Build service options and compute context (always-on config loader path).
1779
- const serviceOptions = getDotenvCliOptions2Options(merged);
1780
- await this.resolveAndLoad(serviceOptions);
1781
- // Global validation: once after Phase C using config sources.
1782
- try {
1783
- const ctx = this.getCtx();
1784
- const dotenv = (ctx?.dotenv ?? {});
1785
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
1786
- const issues = validateEnvAgainstSources(dotenv, sources);
1787
- if (Array.isArray(issues) && issues.length > 0) {
1788
- const logger = (merged.logger ??
1789
- console);
1790
- const emit = logger.error ?? logger.log;
1791
- issues.forEach((m) => {
1792
- emit(m);
1793
- });
1794
- if (merged.strict) {
1795
- // Deterministic failure under strict mode
1796
- process.exit(1);
1797
- }
1798
- }
1799
- }
1800
- catch {
1801
- // Be tolerant: validation errors reported above; unexpected failures here
1802
- // should not crash non-strict flows.
1803
- }
1804
- });
1805
- // Also handle root-level flows (no subcommand) so option-aliases can run
1806
- // with the same merged options and context without duplicating logic.
1807
- this.hook('preAction', async (thisCommand) => {
1808
- const raw = thisCommand.opts();
1809
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1810
- thisCommand.getDotenvCliOptions =
1811
- merged;
1812
- this._setOptionsBag(merged);
1813
- // Avoid duplicate heavy work if a context is already present.
1814
- if (!this.getCtx()) {
1807
+ /**
1808
+ * Install preSubcommand/preAction hooks that:
1809
+ * - Merge options (parent round-trip + current invocation) using resolveCliOptions.
1810
+ * - Persist the merged bag on the current command and on the host (for ergonomics).
1811
+ * - Compute the dotenv context once via resolveAndLoad(serviceOptions).
1812
+ * - Validate the composed env against discovered config (warn or --strict fail).
1813
+ */
1814
+ passOptions(defaults) {
1815
+ const d = (defaults ?? baseRootOptionDefaults);
1816
+ this.hook('preSubcommand', async (thisCommand) => {
1817
+ const raw = thisCommand.opts();
1818
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1819
+ // Persist merged options (for nested behavior and ergonomic access).
1820
+ thisCommand.getDotenvCliOptions =
1821
+ merged;
1822
+ this._setOptionsBag(merged);
1823
+ // Build service options and compute context (always-on loader path).
1815
1824
  const serviceOptions = getDotenvCliOptions2Options(merged);
1816
1825
  await this.resolveAndLoad(serviceOptions);
1826
+ // Global validation: once after Phase C using config sources.
1817
1827
  try {
1818
1828
  const ctx = this.getCtx();
1819
1829
  const dotenv = (ctx?.dotenv ?? {});
@@ -1832,12 +1842,46 @@ GetDotenvCli.prototype.passOptions = function (defaults) {
1832
1842
  }
1833
1843
  }
1834
1844
  catch {
1835
- // Tolerate validation side-effects in non-strict mode
1845
+ // Be tolerant: do not crash non-strict flows on unexpected validator failures.
1836
1846
  }
1837
- }
1838
- });
1839
- return this;
1840
- };
1847
+ });
1848
+ // Also handle root-level flows (no subcommand) so option-aliases can run
1849
+ // with the same merged options and context without duplicating logic.
1850
+ this.hook('preAction', async (thisCommand) => {
1851
+ const raw = thisCommand.opts();
1852
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1853
+ thisCommand.getDotenvCliOptions =
1854
+ merged;
1855
+ this._setOptionsBag(merged);
1856
+ // Avoid duplicate heavy work if a context is already present.
1857
+ if (!this.getCtx()) {
1858
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1859
+ await this.resolveAndLoad(serviceOptions);
1860
+ try {
1861
+ const ctx = this.getCtx();
1862
+ const dotenv = (ctx?.dotenv ?? {});
1863
+ const sources = await resolveGetDotenvConfigSources(import.meta.url);
1864
+ const issues = validateEnvAgainstSources(dotenv, sources);
1865
+ if (Array.isArray(issues) && issues.length > 0) {
1866
+ const logger = (merged
1867
+ .logger ?? console);
1868
+ const emit = logger.error ?? logger.log;
1869
+ issues.forEach((m) => {
1870
+ emit(m);
1871
+ });
1872
+ if (merged.strict) {
1873
+ process.exit(1);
1874
+ }
1875
+ }
1876
+ }
1877
+ catch {
1878
+ // Tolerate validation side-effects in non-strict mode.
1879
+ }
1880
+ }
1881
+ });
1882
+ return this;
1883
+ }
1884
+ }
1841
1885
 
1842
1886
  // Minimal tokenizer for shell-off execution:
1843
1887
  // Splits by whitespace while preserving quoted segments (single or double quotes).
@@ -2072,34 +2116,6 @@ const buildSpawnEnv = (base, overlay) => {
2072
2116
  return out;
2073
2117
  };
2074
2118
 
2075
- /** src/cliHost/definePlugin.ts
2076
- * Plugin contracts for the GetDotenv CLI host.
2077
- *
2078
- * This module exposes a structural public interface for the host that plugins
2079
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
2080
- * nominal class identity issues (private fields) in downstream consumers.
2081
- */
2082
- /**
2083
- * Define a GetDotenv CLI plugin with compositional helpers.
2084
- *
2085
- * @example
2086
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
2087
- * .use(childA)
2088
- * .use(childB);
2089
- */
2090
- const definePlugin = (spec) => {
2091
- const { children = [], ...rest } = spec;
2092
- const plugin = {
2093
- ...rest,
2094
- children: [...children],
2095
- use(child) {
2096
- this.children.push(child);
2097
- return this;
2098
- },
2099
- };
2100
- return plugin;
2101
- };
2102
-
2103
2119
  /**
2104
2120
  * Batch services (neutral): resolve command and shell settings.
2105
2121
  * Shared by the generator path and the batch plugin to avoid circular deps.
@@ -3170,7 +3186,7 @@ const cmdPlugin = (options = {}) => definePlugin({
3170
3186
  const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
3171
3187
  const cmd = new Command()
3172
3188
  .name('cmd')
3173
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
3189
+ .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
3174
3190
  .configureHelp({ showGlobalOptions: true })
3175
3191
  .enablePositionalOptions()
3176
3192
  .passThroughOptions()
@@ -3758,7 +3774,7 @@ const batchCommand = new Command()
3758
3774
 
3759
3775
  const cmdCommand = new Command()
3760
3776
  .name('cmd')
3761
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
3777
+ .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
3762
3778
  .configureHelp({ showGlobalOptions: true })
3763
3779
  .enablePositionalOptions()
3764
3780
  .passThroughOptions()