@karmaniverous/get-dotenv 5.2.5 → 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,14 +1,266 @@
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';
11
11
 
12
+ /**
13
+ * Dotenv expansion utilities.
14
+ *
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.
24
+ */
25
+ /**
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.
81
+ *
82
+ * @example
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.
93
+ */
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
+ }
161
+ };
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;
262
+ };
263
+
12
264
  // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
13
265
  const baseRootOptionDefaults = {
14
266
  dotenvToken: '.env',
@@ -36,8 +288,6 @@ const baseRootOptionDefaults = {
36
288
  // (debug/log/exclude* resolved via flag utils)
37
289
  };
38
290
 
39
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
40
-
41
291
  /** @internal */
42
292
  const isPlainObject$1 = (value) => value !== null &&
43
293
  typeof value === 'object' &&
@@ -80,134 +330,130 @@ const defaultsDeep = (...layers) => {
80
330
  return result;
81
331
  };
82
332
 
83
- // src/GetDotenvOptions.ts
84
- const getDotenvOptionsFilename = 'getdotenv.config.json';
85
333
  /**
86
- * Converts programmatic CLI options to `getDotenv` options. *
87
- * @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).
88
338
  *
89
- * @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
+ * ```
90
348
  */
91
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
92
- /**
93
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
94
- *
95
- * - 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`
96
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
97
- * - Drops CLI-only keys that have no programmatic equivalent.
98
- *
99
- * @remarks
100
- * Follows exact-optional semantics by not emitting undefined-valued entries.
101
- */
102
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
103
- // Create a shallow copy then delete optional CLI-only keys if present.
104
- const restObj = { ...rest };
105
- delete restObj.debug;
106
- delete restObj.scripts;
107
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
108
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
109
- let parsedVars;
110
- if (typeof vars === 'string') {
111
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
112
- ? RegExp(varsAssignorPattern)
113
- : (varsAssignor ?? '=')));
114
- parsedVars = Object.fromEntries(kvPairs);
115
- }
116
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
117
- // Keep only string or undefined values to match ProcessEnv.
118
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
119
- parsedVars = Object.fromEntries(entries);
120
- }
121
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
122
- // expectations and the compat test assertions.
123
- if (parsedVars) {
124
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
125
- }
126
- // Tolerate paths as either a delimited string or string[]
127
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
128
- // under the RootOptionsShape (which declares paths as string | undefined).
129
- const pathsAny = paths;
130
- const pathsOut = Array.isArray(pathsAny)
131
- ? pathsAny.filter((p) => typeof p === 'string')
132
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
133
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
134
- return {
135
- ...restObj,
136
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
137
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
138
- };
139
- };
140
- const resolveGetDotenvOptions = async (customOptions) => {
141
- /**
142
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
143
- *
144
- * 1. Base defaults derived from the CLI generator defaults
145
- * ({@link baseGetDotenvCliOptions}).
146
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
147
- * package root (if present).
148
- * 3. The provided {@link customOptions}.
149
- *
150
- * The result preserves explicit empty values and drops only `undefined`.
151
- *
152
- * @returns Fully-resolved {@link GetDotenvOptions}.
153
- *
154
- * @example
155
- * ```ts
156
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
157
- * ```
158
- */
159
- const localPkgDir = await packageDirectory();
160
- const localOptionsPath = localPkgDir
161
- ? join(localPkgDir, getDotenvOptionsFilename)
162
- : undefined;
163
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
164
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
165
- : {});
166
- // Merge order: base < local < custom (custom has highest precedence)
167
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
168
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
169
- const result = defaultsDeep(defaultsFromCli, customOptions);
170
- return {
171
- ...result, // Keep explicit empty strings/zeros; drop only undefined
172
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
173
- };
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;
174
408
  };
175
409
 
176
410
  /**
177
- * Zod schemas for programmatic GetDotenv options.
178
- *
179
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
180
- * Legacy paths continue to use existing types/logic. The new plugin host will
181
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
182
- * 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.
183
414
  */
184
- // Minimal process env representation: string values or undefined to indicate "unset".
185
- const processEnvSchema = z.record(z.string(), z.string().optional());
186
- // RAW: all fields optional — undefined means "inherit" from lower layers.
187
- const getDotenvOptionsSchemaRaw = z.object({
188
- defaultEnv: z.string().optional(),
189
- dotenvToken: z.string().optional(),
190
- dynamicPath: z.string().optional(),
191
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
192
- dynamic: z.record(z.string(), z.unknown()).optional(),
193
- env: z.string().optional(),
194
- excludeDynamic: z.boolean().optional(),
195
- excludeEnv: z.boolean().optional(),
196
- excludeGlobal: z.boolean().optional(),
197
- excludePrivate: z.boolean().optional(),
198
- excludePublic: z.boolean().optional(),
199
- loadProcess: z.boolean().optional(),
200
- log: z.boolean().optional(),
201
- outputPath: z.string().optional(),
202
- paths: z.array(z.string()).optional(),
203
- privateToken: z.string().optional(),
204
- vars: processEnvSchema.optional(),
205
- // Host-only feature flag: guarded integration of config loader/overlay
206
- useConfigLoader: z.boolean().optional(),
207
- });
208
- // RESOLVED: service-boundary contract (post-inheritance).
209
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
210
- 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
+ };
211
457
 
212
458
  /**
213
459
  * Zod schemas for configuration files discovered by the new loader.
@@ -447,160 +693,211 @@ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
447
693
  };
448
694
 
449
695
  /**
450
- * Dotenv expansion utilities.
451
- *
452
- * This module implements recursive expansion of environment-variable
453
- * references in strings and records. It supports both whitespace and
454
- * bracket syntaxes with optional defaults:
455
- *
456
- * - Whitespace: `$VAR[:default]`
457
- * - Bracketed: `${VAR[:default]}`
696
+ * Validate a composed env against config-provided validation surfaces.
697
+ * Precedence for validation definitions:
698
+ * project.local -\> project.public -\> packaged
458
699
  *
459
- * Escaped dollar signs (`\$`) are preserved.
460
- * Unknown variables resolve to empty string unless a default is provided.
461
- */
462
- /**
463
- * Like String.prototype.search but returns the last index.
464
- * @internal
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.
465
704
  */
466
- const searchLast = (str, rgx) => {
467
- const matches = Array.from(str.matchAll(rgx));
468
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
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 [];
469
749
  };
470
- const replaceMatch = (value, match, ref) => {
750
+
751
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
752
+
753
+ // src/GetDotenvOptions.ts
754
+ const getDotenvOptionsFilename = 'getdotenv.config.json';
755
+ /**
756
+ * Converts programmatic CLI options to `getDotenv` options. *
757
+ * @param cliOptions - CLI options. Defaults to `{}`.
758
+ *
759
+ * @returns `getDotenv` options.
760
+ */
761
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
471
762
  /**
472
- * @internal
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.
473
771
  */
474
- const group = match[0];
475
- const key = match[1];
476
- const defaultValue = match[2];
477
- if (!key)
478
- return value;
479
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
480
- return interpolate(replacement, ref);
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
+ };
481
809
  };
482
- const interpolate = (value = '', ref = {}) => {
810
+ const resolveGetDotenvOptions = async (customOptions) => {
483
811
  /**
484
- * @internal
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
+ * ```
485
828
  */
486
- // if value is falsy, return it as is
487
- if (!value)
488
- return value;
489
- // get position of last unescaped dollar sign
490
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
491
- // return value if none found
492
- if (lastUnescapedDollarSignIndex === -1)
493
- return value;
494
- // evaluate the value tail
495
- const tail = value.slice(lastUnescapedDollarSignIndex);
496
- // find whitespace pattern: $KEY:DEFAULT
497
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
498
- const whitespaceMatch = whitespacePattern.exec(tail);
499
- if (whitespaceMatch != null)
500
- return replaceMatch(value, whitespaceMatch, ref);
501
- else {
502
- // find bracket pattern: ${KEY:DEFAULT}
503
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
504
- const bracketMatch = bracketPattern.exec(tail);
505
- if (bracketMatch != null)
506
- return replaceMatch(value, bracketMatch, ref);
507
- }
508
- return value;
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
+ };
509
844
  };
845
+
510
846
  /**
511
- * Recursively expands environment variables in a string. Variables may be
512
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
513
- * Unknown variables will expand to an empty string.
514
- *
515
- * @param value - The string to expand.
516
- * @param ref - The reference object to use for variable expansion.
517
- * @returns The expanded string.
518
- *
519
- * @example
520
- * ```ts
521
- * process.env.FOO = 'bar';
522
- * dotenvExpand('Hello $FOO'); // "Hello bar"
523
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
524
- * ```
847
+ * Zod schemas for programmatic GetDotenv options.
525
848
  *
526
- * @remarks
527
- * The expansion is recursive. If a referenced variable itself contains
528
- * references, those will also be expanded until a stable value is reached.
529
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
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.
530
853
  */
531
- const dotenvExpand = (value, ref = process.env) => {
532
- const result = interpolate(value, ref);
533
- return result ? result.replace(/\\\$/g, '$') : undefined;
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;
881
+
882
+ const applyKv = (current, kv) => {
883
+ if (!kv || Object.keys(kv).length === 0)
884
+ return current;
885
+ const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
886
+ return { ...current, ...expanded };
887
+ };
888
+ const applyConfigSlice = (current, cfg, env) => {
889
+ if (!cfg)
890
+ return current;
891
+ // kind axis: global then env (env overrides global)
892
+ const afterGlobal = applyKv(current, cfg.vars);
893
+ const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
894
+ return applyKv(afterGlobal, envKv);
534
895
  };
535
896
  /**
536
- * Recursively expands environment variables in the values of a JSON object.
537
- * Variables may be presented with optional default as `$VAR[:default]` or
538
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
539
- *
540
- * @param values - The values object to expand.
541
- * @param options - Expansion options.
542
- * @returns The value object with expanded string values.
543
- *
544
- * @example
545
- * ```ts
546
- * process.env.FOO = 'bar';
547
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
548
- * // => { A: "bar", B: "xbary" }
549
- * ```
550
- *
551
- * @remarks
552
- * Options:
553
- * - ref: The reference object to use for expansion (defaults to process.env).
554
- * - progressive: Whether to progressively add expanded values to the set of
555
- * reference keys.
556
- *
557
- * When `progressive` is true, each expanded key becomes available for
558
- * subsequent expansions in the same object (left-to-right by object key order).
559
- */
560
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
561
- const { ref = process.env, progressive = false } = options;
562
- acc[key] = dotenvExpand(values[key], {
563
- ...ref,
564
- ...(progressive ? acc : {}),
565
- });
566
- return acc;
567
- }, {});
568
- /**
569
- * Recursively expands environment variables in a string using `process.env` as
570
- * the expansion reference. Variables may be presented with optional default as
571
- * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
572
- * empty string.
573
- *
574
- * @param value - The string to expand.
575
- * @returns The expanded string.
576
- *
577
- * @example
578
- * ```ts
579
- * process.env.FOO = 'bar';
580
- * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
581
- * ```
582
- */
583
- const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
584
-
585
- const applyKv = (current, kv) => {
586
- if (!kv || Object.keys(kv).length === 0)
587
- return current;
588
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
589
- return { ...current, ...expanded };
590
- };
591
- const applyConfigSlice = (current, cfg, env) => {
592
- if (!cfg)
593
- return current;
594
- // kind axis: global then env (env overrides global)
595
- const afterGlobal = applyKv(current, cfg.vars);
596
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
597
- return applyKv(afterGlobal, envKv);
598
- };
599
- /**
600
- * Overlay config-provided values onto a base ProcessEnv using precedence axes:
601
- * - kind: env \> global
602
- * - privacy: local \> public
603
- * - source: project \> packaged \> base
897
+ * Overlay config-provided values onto a base ProcessEnv using precedence axes:
898
+ * - kind: env \> global
899
+ * - privacy: local \> public
900
+ * - source: project \> packaged \> base
604
901
  *
605
902
  * Programmatic explicit vars (if provided) override all config slices.
606
903
  * Progressive expansion is applied within each slice.
@@ -1173,7 +1470,7 @@ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1173
1470
  *
1174
1471
  * NOTE: This host is additive and does not alter the legacy CLI.
1175
1472
  */
1176
- class GetDotenvCli extends Command {
1473
+ let GetDotenvCli$1 = class GetDotenvCli extends Command {
1177
1474
  /** Registered top-level plugins (composition happens via .use()) */
1178
1475
  _plugins = [];
1179
1476
  /** One-time installation guard */
@@ -1251,560 +1548,184 @@ class GetDotenvCli extends Command {
1251
1548
  }
1252
1549
  /**
1253
1550
  * Retrieve the merged root CLI options bag (if set by passOptions()).
1254
- * Downstream-safe: no generics required.
1255
- */
1256
- getOptions() {
1257
- return this[OPTS_SYMBOL];
1258
- }
1259
- /** Internal: set the merged root options bag for this run. */
1260
- _setOptionsBag(bag) {
1261
- this[OPTS_SYMBOL] = bag;
1262
- }
1263
- /** * Convenience helper to create a namespaced subcommand.
1264
- */
1265
- ns(name) {
1266
- return this.command(name);
1267
- }
1268
- /**
1269
- * Tag options added during the provided callback as 'app' for grouped help.
1270
- * Allows downstream apps to demarcate their root-level options.
1271
- */
1272
- tagAppOptions(fn) {
1273
- const root = this;
1274
- const originalAddOption = root.addOption.bind(root);
1275
- const originalOption = root.option.bind(root);
1276
- const tagLatest = (cmd, group) => {
1277
- const optsArr = cmd.options;
1278
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1279
- const last = optsArr[optsArr.length - 1];
1280
- last.__group = group;
1281
- }
1282
- };
1283
- root.addOption = function patchedAdd(opt) {
1284
- opt.__group = 'app';
1285
- return originalAddOption(opt);
1286
- };
1287
- root.option = function patchedOption(...args) {
1288
- const ret = originalOption(...args);
1289
- tagLatest(this, 'app');
1290
- return ret;
1291
- };
1292
- try {
1293
- return fn(root);
1294
- }
1295
- finally {
1296
- root.addOption = originalAddOption;
1297
- root.option = originalOption;
1298
- }
1299
- }
1300
- /**
1301
- * Branding helper: set CLI name/description/version and optional help header.
1302
- * If version is omitted and importMetaUrl is provided, attempts to read the
1303
- * nearest package.json version (best-effort; non-fatal on failure).
1304
- */
1305
- async brand(args) {
1306
- const { name, description, version, importMetaUrl, helpHeader } = args;
1307
- if (typeof name === 'string' && name.length > 0)
1308
- this.name(name);
1309
- if (typeof description === 'string')
1310
- this.description(description);
1311
- let v = version;
1312
- if (!v && importMetaUrl) {
1313
- try {
1314
- const fromUrl = fileURLToPath(importMetaUrl);
1315
- const pkgDir = await packageDirectory({ cwd: fromUrl });
1316
- if (pkgDir) {
1317
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1318
- const pkg = JSON.parse(txt);
1319
- if (pkg.version)
1320
- v = pkg.version;
1321
- }
1322
- }
1323
- catch {
1324
- // best-effort only
1325
- }
1326
- }
1327
- if (v)
1328
- this.version(v);
1329
- // Help header:
1330
- // - If caller provides helpHeader, use it.
1331
- // - Otherwise, when a version is known, default to "<name> v<version>".
1332
- if (typeof helpHeader === 'string') {
1333
- this[HELP_HEADER_SYMBOL] = helpHeader;
1334
- }
1335
- else if (v) {
1336
- // Use the current command name (possibly overridden by 'name' above).
1337
- const header = `${this.name()} v${v}`;
1338
- this[HELP_HEADER_SYMBOL] = header;
1339
- }
1340
- return this;
1341
- }
1342
- /**
1343
- * Register a plugin for installation (parent level).
1344
- * Installation occurs on first resolveAndLoad() (or explicit install()).
1345
- */
1346
- use(plugin) {
1347
- this._plugins.push(plugin);
1348
- // Immediately run setup so subcommands exist before parsing.
1349
- const setupOne = (p) => {
1350
- p.setup(this);
1351
- for (const child of p.children)
1352
- setupOne(child);
1353
- };
1354
- setupOne(plugin);
1355
- return this;
1356
- }
1357
- /**
1358
- * Install all registered plugins in parent → children (pre-order).
1359
- * Runs only once per CLI instance.
1360
- */
1361
- async install() {
1362
- // Setup is performed immediately in use(); here we only guard for afterResolve.
1363
- this._installed = true;
1364
- // Satisfy require-await without altering behavior.
1365
- await Promise.resolve();
1366
- }
1367
- /**
1368
- * Run afterResolve hooks for all plugins (parent → children).
1369
- */
1370
- async _runAfterResolve(ctx) {
1371
- const run = async (p) => {
1372
- if (p.afterResolve)
1373
- await p.afterResolve(this, ctx);
1374
- for (const child of p.children)
1375
- await run(child);
1376
- };
1377
- for (const p of this._plugins)
1378
- await run(p);
1379
- }
1380
- // Render App/Plugin grouped options appended after default help.
1381
- #renderOptionGroups(cmd) {
1382
- const all = cmd.options ?? [];
1383
- const byGroup = new Map();
1384
- for (const o of all) {
1385
- const opt = o;
1386
- const g = opt.__group;
1387
- if (!g || g === 'base')
1388
- continue; // base handled by default help
1389
- const rows = byGroup.get(g) ?? [];
1390
- rows.push({
1391
- flags: opt.flags ?? '',
1392
- description: opt.description ?? '',
1393
- });
1394
- byGroup.set(g, rows);
1395
- }
1396
- if (byGroup.size === 0)
1397
- return '';
1398
- const renderRows = (title, rows) => {
1399
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1400
- // Sort within group: short-aliased flags first
1401
- rows.sort((a, b) => {
1402
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1403
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1404
- return bS - aS || a.flags.localeCompare(b.flags);
1405
- });
1406
- const lines = rows
1407
- .map((r) => {
1408
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1409
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1410
- })
1411
- .join('\n');
1412
- return `\n${title}:\n${lines}\n`;
1413
- };
1414
- let out = '';
1415
- // App options (if any)
1416
- const app = byGroup.get('app');
1417
- if (app && app.length > 0) {
1418
- out += renderRows('App options', app);
1419
- }
1420
- // Plugin groups sorted by id
1421
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1422
- pluginKeys.sort((a, b) => a.localeCompare(b));
1423
- for (const k of pluginKeys) {
1424
- const id = k.slice('plugin:'.length) || '(unknown)';
1425
- const rows = byGroup.get(k) ?? [];
1426
- if (rows.length > 0) {
1427
- out += renderRows(`Plugin options — ${id}`, rows);
1428
- }
1429
- }
1430
- return out;
1431
- }
1432
- }
1433
-
1434
- /**
1435
- * Validate a composed env against config-provided validation surfaces.
1436
- * Precedence for validation definitions:
1437
- * project.local -\> project.public -\> packaged
1438
- *
1439
- * Behavior:
1440
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
1441
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
1442
- * - Returns a flat list of issue strings; caller decides warn vs fail.
1443
- */
1444
- const validateEnvAgainstSources = (finalEnv, sources) => {
1445
- const pick = (getter) => {
1446
- const pl = sources.project?.local;
1447
- const pp = sources.project?.public;
1448
- const pk = sources.packaged;
1449
- return ((pl && getter(pl)) ||
1450
- (pp && getter(pp)) ||
1451
- (pk && getter(pk)) ||
1452
- undefined);
1453
- };
1454
- const schema = pick((cfg) => cfg['schema']);
1455
- if (schema &&
1456
- typeof schema.safeParse === 'function') {
1457
- try {
1458
- const parsed = schema.safeParse(finalEnv);
1459
- if (!parsed.success) {
1460
- // Try to render zod-style issues when available.
1461
- const err = parsed.error;
1462
- const issues = Array.isArray(err.issues) && err.issues.length > 0
1463
- ? err.issues.map((i) => {
1464
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
1465
- const msg = i.message ?? 'Invalid value';
1466
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
1467
- })
1468
- : ['[schema] validation failed'];
1469
- return issues;
1470
- }
1471
- return [];
1472
- }
1473
- catch {
1474
- // If schema invocation fails, surface a single diagnostic.
1475
- return [
1476
- '[schema] validation failed (unable to execute schema.safeParse)',
1477
- ];
1478
- }
1479
- }
1480
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
1481
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
1482
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
1483
- if (missing.length > 0) {
1484
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
1485
- }
1486
- }
1487
- return [];
1488
- };
1489
-
1490
- /**
1491
- * Attach legacy root flags to a Commander program.
1492
- * Uses provided defaults to render help labels without coupling to generators.
1493
- */
1494
- const attachRootOptions = (program, defaults, opts) => {
1495
- // Install temporary wrappers to tag all options added here as "base".
1496
- const GROUP = 'base';
1497
- const tagLatest = (cmd, group) => {
1498
- const optsArr = cmd.options;
1499
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1500
- const last = optsArr[optsArr.length - 1];
1501
- last.__group = group;
1502
- }
1503
- };
1504
- const originalAddOption = program.addOption.bind(program);
1505
- const originalOption = program.option.bind(program);
1506
- program.addOption = function patchedAdd(opt) {
1507
- // Tag before adding, in case consumers inspect the Option directly.
1508
- opt.__group = GROUP;
1509
- const ret = originalAddOption(opt);
1510
- return ret;
1511
- };
1512
- program.option = function patchedOption(...args) {
1513
- const ret = originalOption(...args);
1514
- tagLatest(this, GROUP);
1515
- return ret;
1516
- };
1517
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1518
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1519
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1520
- // Build initial chain.
1521
- let p = program
1522
- .enablePositionalOptions()
1523
- .passThroughOptions()
1524
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1525
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1526
- ['KEY1', 'VAL1'],
1527
- ['KEY2', 'VAL2'],
1528
- ]
1529
- .map((v) => v.join(va))
1530
- .join(vd)}`, dotenvExpandFromProcessEnv);
1531
- // Optional legacy root command flag (kept for generated CLI compatibility).
1532
- // Default is OFF; the generator opts in explicitly.
1533
- if (opts?.includeCommandOption === true) {
1534
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1535
- }
1536
- p = p
1537
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
1538
- .addOption(new Option('-s, --shell [string]', (() => {
1539
- let defaultLabel = '';
1540
- if (shell !== undefined) {
1541
- if (typeof shell === 'boolean') {
1542
- defaultLabel = ' (default OS shell)';
1543
- }
1544
- else if (typeof shell === 'string') {
1545
- // Safe string interpolation
1546
- defaultLabel = ` (default ${shell})`;
1547
- }
1548
- }
1549
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
1550
- })()).conflicts('shellOff'))
1551
- .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
1552
- .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
1553
- .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
1554
- .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1555
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1556
- ? ' (default)'
1557
- : ''}`).conflicts('excludeAllOff'))
1558
- .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
1559
- .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
1560
- .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
1561
- .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
1562
- .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
1563
- .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
1564
- .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
1565
- .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
1566
- .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
1567
- .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
1568
- .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
1569
- .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
1570
- .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
1571
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
1572
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
1573
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
1574
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
1575
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
1576
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
1577
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
1578
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
1579
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
1580
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
1581
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
1582
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
1583
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1584
- // Hidden scripts pipe-through (stringified)
1585
- .addOption(new Option('--scripts <string>')
1586
- .default(JSON.stringify(scripts))
1587
- .hideHelp());
1588
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1589
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1590
- // Validation: strict mode fails on env validation issues (warn by default).
1591
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1592
- // Entropy diagnostics (presentation-only)
1593
- p = p
1594
- .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
1595
- .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
1596
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
1597
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
1598
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
1599
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1600
- // Restore original methods to avoid tagging future additions outside base.
1601
- program.addOption = originalAddOption;
1602
- program.option = originalOption;
1603
- return p;
1604
- };
1605
-
1606
- /**
1607
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1608
- * - If the user explicitly enabled the flag, return true.
1609
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1610
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
1611
- *
1612
- * @param exclude - The "on" flag value as parsed by Commander.
1613
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1614
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1615
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1616
- *
1617
- * @example
1618
- * ```ts
1619
- * resolveExclusion(undefined, undefined, true); // => true
1620
- * ```
1621
- */
1622
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1623
- /**
1624
- * Resolve an optional flag with "--exclude-all" overrides.
1625
- * If excludeAll is set and the individual "...-off" is not, force true.
1626
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1627
- * Otherwise, adopt the default (true → set; false/undefined → unset).
1628
- *
1629
- * @param exclude - Individual include/exclude flag.
1630
- * @param excludeOff - Individual "...-off" flag.
1631
- * @param defaultValue - Default for the individual flag.
1632
- * @param excludeAll - Global "exclude-all" flag.
1633
- * @param excludeAllOff - Global "exclude-all-off" flag.
1634
- *
1635
- * @example
1636
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1637
- */
1638
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1639
- // Order of precedence:
1640
- // 1) Individual explicit "on" wins outright.
1641
- // 2) Individual explicit "off" wins over any global.
1642
- // 3) Global exclude-all forces true when not explicitly turned off.
1643
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1644
- // 5) Fall back to the default (true => set; false/undefined => unset).
1645
- (() => {
1646
- // Individual "on"
1647
- if (exclude === true)
1648
- return true;
1649
- // Individual "off"
1650
- if (excludeOff === true)
1651
- return undefined;
1652
- // Global "exclude-all" ON (unless explicitly turned off)
1653
- if (excludeAll === true)
1654
- return true;
1655
- // Global "exclude-all-off" (unless explicitly enabled)
1656
- if (excludeAllOff === true)
1657
- return undefined;
1658
- // Default
1659
- return defaultValue ? true : undefined;
1660
- })();
1661
- /**
1662
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1663
- * delete when undefined; assign when defined — without requiring an index signature on T.
1664
- *
1665
- * @typeParam T - Target object type.
1666
- * @param obj - The object to write to.
1667
- * @param key - The optional boolean property key of {@link T}.
1668
- * @param value - The value to set or `undefined` to unset.
1669
- *
1670
- * @remarks
1671
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1672
- */
1673
- const setOptionalFlag = (obj, key, value) => {
1674
- const target = obj;
1675
- const k = key;
1676
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1677
- if (value === undefined)
1678
- delete target[k];
1679
- else
1680
- target[k] = value;
1681
- };
1682
-
1683
- /**
1684
- * Merge and normalize raw Commander options (current + parent + defaults)
1685
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1686
- * avoid cross-layer coupling; callers may cast as needed.
1687
- */
1688
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1689
- const parent = typeof parentJson === 'string' && parentJson.length > 0
1690
- ? JSON.parse(parentJson)
1691
- : undefined;
1692
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1693
- const current = { ...rest };
1694
- if (typeof scripts === 'string') {
1695
- try {
1696
- current.scripts = JSON.parse(scripts);
1697
- }
1698
- catch {
1699
- // ignore parse errors; leave scripts undefined
1700
- }
1551
+ * Downstream-safe: no generics required.
1552
+ */
1553
+ getOptions() {
1554
+ return this[OPTS_SYMBOL];
1701
1555
  }
1702
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1703
- const d = defaults;
1704
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1705
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1706
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1707
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1708
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1709
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1710
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1711
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1712
- // warnEntropy (tri-state)
1713
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1714
- // Normalize shell for predictability: explicit default shell per OS.
1715
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1716
- let resolvedShell = merged.shell;
1717
- if (shellOff)
1718
- resolvedShell = false;
1719
- else if (resolvedShell === true || resolvedShell === undefined) {
1720
- resolvedShell = defaultShell;
1556
+ /** Internal: set the merged root options bag for this run. */
1557
+ _setOptionsBag(bag) {
1558
+ this[OPTS_SYMBOL] = bag;
1721
1559
  }
1722
- else if (typeof resolvedShell !== 'string' &&
1723
- typeof defaults.shell === 'string') {
1724
- resolvedShell = defaults.shell;
1560
+ /** * Convenience helper to create a namespaced subcommand.
1561
+ */
1562
+ ns(name) {
1563
+ return this.command(name);
1725
1564
  }
1726
- merged.shell = resolvedShell;
1727
- const cmd = typeof command === 'string' ? command : undefined;
1728
- return cmd !== undefined ? { merged, command: cmd } : { merged };
1729
- };
1730
-
1731
- GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1732
- const d = (defaults ?? baseRootOptionDefaults);
1733
- attachRootOptions(this, d, opts);
1734
- return this;
1735
- };
1736
- GetDotenvCli.prototype.passOptions = function (defaults) {
1737
- const d = (defaults ?? baseRootOptionDefaults);
1738
- this.hook('preSubcommand', async (thisCommand) => {
1739
- const raw = thisCommand.opts();
1740
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1741
- // Persist merged options for nested invocations (batch exec).
1742
- thisCommand.getDotenvCliOptions =
1743
- merged;
1744
- // Also store on the host for downstream ergonomic accessors.
1745
- this._setOptionsBag(merged);
1746
- // Build service options and compute context (always-on config loader path).
1747
- const serviceOptions = getDotenvCliOptions2Options(merged);
1748
- await this.resolveAndLoad(serviceOptions);
1749
- // Global validation: once after Phase C using config sources.
1750
- try {
1751
- const ctx = this.getCtx();
1752
- const dotenv = (ctx?.dotenv ?? {});
1753
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
1754
- const issues = validateEnvAgainstSources(dotenv, sources);
1755
- if (Array.isArray(issues) && issues.length > 0) {
1756
- const logger = (merged.logger ??
1757
- console);
1758
- const emit = logger.error ?? logger.log;
1759
- issues.forEach((m) => {
1760
- emit(m);
1761
- });
1762
- if (merged.strict) {
1763
- // Deterministic failure under strict mode
1764
- process.exit(1);
1765
- }
1565
+ /**
1566
+ * Tag options added during the provided callback as 'app' for grouped help.
1567
+ * Allows downstream apps to demarcate their root-level options.
1568
+ */
1569
+ tagAppOptions(fn) {
1570
+ const root = this;
1571
+ const originalAddOption = root.addOption.bind(root);
1572
+ const originalOption = root.option.bind(root);
1573
+ const tagLatest = (cmd, group) => {
1574
+ const optsArr = cmd.options;
1575
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
1576
+ const last = optsArr[optsArr.length - 1];
1577
+ last.__group = group;
1766
1578
  }
1579
+ };
1580
+ root.addOption = function patchedAdd(opt) {
1581
+ opt.__group = 'app';
1582
+ return originalAddOption(opt);
1583
+ };
1584
+ root.option = function patchedOption(...args) {
1585
+ const ret = originalOption(...args);
1586
+ tagLatest(this, 'app');
1587
+ return ret;
1588
+ };
1589
+ try {
1590
+ return fn(root);
1767
1591
  }
1768
- catch {
1769
- // Be tolerant: validation errors reported above; unexpected failures here
1770
- // should not crash non-strict flows.
1592
+ finally {
1593
+ root.addOption = originalAddOption;
1594
+ root.option = originalOption;
1771
1595
  }
1772
- });
1773
- // Also handle root-level flows (no subcommand) so option-aliases can run
1774
- // with the same merged options and context without duplicating logic.
1775
- this.hook('preAction', async (thisCommand) => {
1776
- const raw = thisCommand.opts();
1777
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1778
- thisCommand.getDotenvCliOptions =
1779
- merged;
1780
- this._setOptionsBag(merged);
1781
- // Avoid duplicate heavy work if a context is already present.
1782
- if (!this.getCtx()) {
1783
- const serviceOptions = getDotenvCliOptions2Options(merged);
1784
- await this.resolveAndLoad(serviceOptions);
1596
+ }
1597
+ /**
1598
+ * Branding helper: set CLI name/description/version and optional help header.
1599
+ * If version is omitted and importMetaUrl is provided, attempts to read the
1600
+ * nearest package.json version (best-effort; non-fatal on failure).
1601
+ */
1602
+ async brand(args) {
1603
+ const { name, description, version, importMetaUrl, helpHeader } = args;
1604
+ if (typeof name === 'string' && name.length > 0)
1605
+ this.name(name);
1606
+ if (typeof description === 'string')
1607
+ this.description(description);
1608
+ let v = version;
1609
+ if (!v && importMetaUrl) {
1785
1610
  try {
1786
- const ctx = this.getCtx();
1787
- const dotenv = (ctx?.dotenv ?? {});
1788
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
1789
- const issues = validateEnvAgainstSources(dotenv, sources);
1790
- if (Array.isArray(issues) && issues.length > 0) {
1791
- const logger = (merged
1792
- .logger ?? console);
1793
- const emit = logger.error ?? logger.log;
1794
- issues.forEach((m) => {
1795
- emit(m);
1796
- });
1797
- if (merged.strict) {
1798
- process.exit(1);
1799
- }
1611
+ const fromUrl = fileURLToPath(importMetaUrl);
1612
+ const pkgDir = await packageDirectory({ cwd: fromUrl });
1613
+ if (pkgDir) {
1614
+ const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1615
+ const pkg = JSON.parse(txt);
1616
+ if (pkg.version)
1617
+ v = pkg.version;
1800
1618
  }
1801
1619
  }
1802
1620
  catch {
1803
- // Tolerate validation side-effects in non-strict mode
1621
+ // best-effort only
1804
1622
  }
1805
1623
  }
1806
- });
1807
- return this;
1624
+ if (v)
1625
+ this.version(v);
1626
+ // Help header:
1627
+ // - If caller provides helpHeader, use it.
1628
+ // - Otherwise, when a version is known, default to "<name> v<version>".
1629
+ if (typeof helpHeader === 'string') {
1630
+ this[HELP_HEADER_SYMBOL] = helpHeader;
1631
+ }
1632
+ else if (v) {
1633
+ // Use the current command name (possibly overridden by 'name' above).
1634
+ const header = `${this.name()} v${v}`;
1635
+ this[HELP_HEADER_SYMBOL] = header;
1636
+ }
1637
+ return this;
1638
+ }
1639
+ /**
1640
+ * Register a plugin for installation (parent level).
1641
+ * Installation occurs on first resolveAndLoad() (or explicit install()).
1642
+ */
1643
+ use(plugin) {
1644
+ this._plugins.push(plugin);
1645
+ // Immediately run setup so subcommands exist before parsing.
1646
+ const setupOne = (p) => {
1647
+ p.setup(this);
1648
+ for (const child of p.children)
1649
+ setupOne(child);
1650
+ };
1651
+ setupOne(plugin);
1652
+ return this;
1653
+ }
1654
+ /**
1655
+ * Install all registered plugins in parent → children (pre-order).
1656
+ * Runs only once per CLI instance.
1657
+ */
1658
+ async install() {
1659
+ // Setup is performed immediately in use(); here we only guard for afterResolve.
1660
+ this._installed = true;
1661
+ // Satisfy require-await without altering behavior.
1662
+ await Promise.resolve();
1663
+ }
1664
+ /**
1665
+ * Run afterResolve hooks for all plugins (parent → children).
1666
+ */
1667
+ async _runAfterResolve(ctx) {
1668
+ const run = async (p) => {
1669
+ if (p.afterResolve)
1670
+ await p.afterResolve(this, ctx);
1671
+ for (const child of p.children)
1672
+ await run(child);
1673
+ };
1674
+ for (const p of this._plugins)
1675
+ await run(p);
1676
+ }
1677
+ // Render App/Plugin grouped options appended after default help.
1678
+ #renderOptionGroups(cmd) {
1679
+ const all = cmd.options ?? [];
1680
+ const byGroup = new Map();
1681
+ for (const o of all) {
1682
+ const opt = o;
1683
+ const g = opt.__group;
1684
+ if (!g || g === 'base')
1685
+ continue; // base handled by default help
1686
+ const rows = byGroup.get(g) ?? [];
1687
+ rows.push({
1688
+ flags: opt.flags ?? '',
1689
+ description: opt.description ?? '',
1690
+ });
1691
+ byGroup.set(g, rows);
1692
+ }
1693
+ if (byGroup.size === 0)
1694
+ return '';
1695
+ const renderRows = (title, rows) => {
1696
+ const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1697
+ // Sort within group: short-aliased flags first
1698
+ rows.sort((a, b) => {
1699
+ const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1700
+ const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1701
+ return bS - aS || a.flags.localeCompare(b.flags);
1702
+ });
1703
+ const lines = rows
1704
+ .map((r) => {
1705
+ const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1706
+ return ` ${r.flags}${pad}${r.description}`.trimEnd();
1707
+ })
1708
+ .join('\n');
1709
+ return `\n${title}:\n${lines}\n`;
1710
+ };
1711
+ let out = '';
1712
+ // App options (if any)
1713
+ const app = byGroup.get('app');
1714
+ if (app && app.length > 0) {
1715
+ out += renderRows('App options', app);
1716
+ }
1717
+ // Plugin groups sorted by id
1718
+ const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1719
+ pluginKeys.sort((a, b) => a.localeCompare(b));
1720
+ for (const k of pluginKeys) {
1721
+ const id = k.slice('plugin:'.length) || '(unknown)';
1722
+ const rows = byGroup.get(k) ?? [];
1723
+ if (rows.length > 0) {
1724
+ out += renderRows(`Plugin options — ${id}`, rows);
1725
+ }
1726
+ }
1727
+ return out;
1728
+ }
1808
1729
  };
1809
1730
 
1810
1731
  /** src/cliHost/definePlugin.ts
@@ -1835,8 +1756,100 @@ const definePlugin = (spec) => {
1835
1756
  return plugin;
1836
1757
  };
1837
1758
 
1838
- // Ensure attachRootOptions() and passOptions() are available whenever the
1839
- // /cliHost subpath is imported (unconditional for downstream hosts).
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
+ }
1840
1853
  /**
1841
1854
  * Helper to retrieve the merged root options bag from any action handler
1842
1855
  * that only has access to thisCommand. Avoids structural casts.