@karmaniverous/get-dotenv 6.0.0-1 → 6.1.0

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.
Files changed (62) hide show
  1. package/README.md +91 -379
  2. package/dist/cli.d.ts +569 -0
  3. package/dist/cli.mjs +18877 -0
  4. package/dist/cliHost.d.ts +528 -184
  5. package/dist/cliHost.mjs +1977 -1428
  6. package/dist/config.d.ts +191 -14
  7. package/dist/config.mjs +266 -81
  8. package/dist/env-overlay.d.ts +223 -16
  9. package/dist/env-overlay.mjs +185 -4
  10. package/dist/getdotenv.cli.mjs +18025 -3196
  11. package/dist/index.d.ts +623 -256
  12. package/dist/index.mjs +18045 -3206
  13. package/dist/plugins-aws.d.ts +221 -91
  14. package/dist/plugins-aws.mjs +2411 -369
  15. package/dist/plugins-batch.d.ts +300 -103
  16. package/dist/plugins-batch.mjs +2560 -484
  17. package/dist/plugins-cmd.d.ts +229 -106
  18. package/dist/plugins-cmd.mjs +2518 -790
  19. package/dist/plugins-init.d.ts +221 -95
  20. package/dist/plugins-init.mjs +2170 -105
  21. package/dist/plugins.d.ts +246 -125
  22. package/dist/plugins.mjs +17941 -1968
  23. package/dist/templates/cli/index.ts +25 -0
  24. package/{templates/cli/ts → dist/templates/cli}/plugins/hello.ts +13 -9
  25. package/dist/templates/config/js/getdotenv.config.js +20 -0
  26. package/dist/templates/config/json/local/getdotenv.config.local.json +7 -0
  27. package/dist/templates/config/json/public/getdotenv.config.json +9 -0
  28. package/dist/templates/config/public/getdotenv.config.json +8 -0
  29. package/dist/templates/config/ts/getdotenv.config.ts +28 -0
  30. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +7 -0
  31. package/dist/templates/config/yaml/public/getdotenv.config.yaml +7 -0
  32. package/dist/templates/getdotenv.config.js +20 -0
  33. package/dist/templates/getdotenv.config.json +9 -0
  34. package/dist/templates/getdotenv.config.local.json +7 -0
  35. package/dist/templates/getdotenv.config.local.yaml +7 -0
  36. package/dist/templates/getdotenv.config.ts +28 -0
  37. package/dist/templates/getdotenv.config.yaml +7 -0
  38. package/dist/templates/hello.ts +42 -0
  39. package/dist/templates/index.ts +25 -0
  40. package/dist/templates/js/getdotenv.config.js +20 -0
  41. package/dist/templates/json/local/getdotenv.config.local.json +7 -0
  42. package/dist/templates/json/public/getdotenv.config.json +9 -0
  43. package/dist/templates/local/getdotenv.config.local.json +7 -0
  44. package/dist/templates/local/getdotenv.config.local.yaml +7 -0
  45. package/dist/templates/plugins/hello.ts +42 -0
  46. package/dist/templates/public/getdotenv.config.json +9 -0
  47. package/dist/templates/public/getdotenv.config.yaml +7 -0
  48. package/dist/templates/ts/getdotenv.config.ts +28 -0
  49. package/dist/templates/yaml/local/getdotenv.config.local.yaml +7 -0
  50. package/dist/templates/yaml/public/getdotenv.config.yaml +7 -0
  51. package/getdotenv.config.json +1 -19
  52. package/package.json +42 -39
  53. package/templates/cli/index.ts +25 -0
  54. package/templates/cli/plugins/hello.ts +42 -0
  55. package/templates/config/js/getdotenv.config.js +8 -3
  56. package/templates/config/json/public/getdotenv.config.json +0 -3
  57. package/templates/config/public/getdotenv.config.json +0 -5
  58. package/templates/config/ts/getdotenv.config.ts +8 -3
  59. package/templates/config/yaml/public/getdotenv.config.yaml +0 -3
  60. package/dist/plugins-demo.d.ts +0 -204
  61. package/dist/plugins-demo.mjs +0 -496
  62. package/templates/cli/ts/index.ts +0 -9
@@ -1,52 +1,15 @@
1
- import { Command } from 'commander';
1
+ import { Option, Command } from '@commander-js/extra-typings';
2
2
  import { z } from 'zod';
3
- import 'fs-extra';
4
- import path from 'path';
3
+ import path, { join, extname } from 'path';
4
+ import fs from 'fs-extra';
5
5
  import { packageDirectory } from 'package-directory';
6
- import 'url';
7
- import 'yaml';
8
- import 'nanoid';
9
- import 'dotenv';
10
- import 'crypto';
11
- import { globby } from 'globby';
6
+ import url, { fileURLToPath } from 'url';
7
+ import YAML from 'yaml';
8
+ import { createHash } from 'crypto';
9
+ import { nanoid } from 'nanoid';
10
+ import { parse } from 'dotenv';
12
11
  import { execa, execaCommand } from 'execa';
13
-
14
- /**
15
- * Zod schemas for configuration files discovered by the new loader.
16
- *
17
- * Notes:
18
- * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
19
- * - RESOLVED: normalized shapes (paths always string[]).
20
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
21
- */
22
- // String-only env value map
23
- const stringMap = z.record(z.string(), z.string());
24
- const envStringMap = z.record(z.string(), stringMap);
25
- // Allow string[] or single string for "paths" in RAW; normalize later.
26
- const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
27
- const getDotenvConfigSchemaRaw = z.object({
28
- dotenvToken: z.string().optional(),
29
- privateToken: z.string().optional(),
30
- paths: rawPathsSchema,
31
- loadProcess: z.boolean().optional(),
32
- log: z.boolean().optional(),
33
- shell: z.union([z.string(), z.boolean()]).optional(),
34
- scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
35
- requiredKeys: z.array(z.string()).optional(),
36
- schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
37
- vars: stringMap.optional(), // public, global
38
- envVars: envStringMap.optional(), // public, per-env
39
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
40
- dynamic: z.unknown().optional(),
41
- // Per-plugin config bag; validated by plugins/host when used.
42
- plugins: z.record(z.string(), z.unknown()).optional(),
43
- });
44
- // Normalize paths to string[]
45
- const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
46
- getDotenvConfigSchemaRaw.transform((raw) => ({
47
- ...raw,
48
- paths: normalizePaths(raw.paths),
49
- }));
12
+ import { globby } from 'globby';
50
13
 
51
14
  /**
52
15
  * Zod schemas for programmatic GetDotenv options.
@@ -54,10 +17,13 @@ getDotenvConfigSchemaRaw.transform((raw) => ({
54
17
  * Canonical source of truth for options shape. Public types are derived
55
18
  * from these schemas (see consumers via z.output\<\>).
56
19
  */
57
- // Minimal process env representation: string values or undefined to indicate "unset".
20
+ /**
21
+ * Minimal process env representation used by options and helpers.
22
+ * Values may be `undefined` to indicate "unset".
23
+ */
58
24
  const processEnvSchema = z.record(z.string(), z.string().optional());
59
25
  // RAW: all fields optional — undefined means "inherit" from lower layers.
60
- z.object({
26
+ const getDotenvOptionsSchemaRaw = z.object({
61
27
  defaultEnv: z.string().optional(),
62
28
  dotenvToken: z.string().optional(),
63
29
  dynamicPath: z.string().optional(),
@@ -71,89 +37,481 @@ z.object({
71
37
  excludePublic: z.boolean().optional(),
72
38
  loadProcess: z.boolean().optional(),
73
39
  log: z.boolean().optional(),
74
- logger: z.unknown().optional(),
40
+ logger: z.unknown().default(console),
75
41
  outputPath: z.string().optional(),
76
42
  paths: z.array(z.string()).optional(),
77
43
  privateToken: z.string().optional(),
78
44
  vars: processEnvSchema.optional(),
79
45
  });
46
+ /**
47
+ * Resolved programmatic options schema (post-inheritance).
48
+ * For now, this mirrors the RAW schema; future stages may materialize defaults
49
+ * and narrow shapes as resolution is wired into the host.
50
+ */
51
+ const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
80
52
 
81
53
  /**
82
- * Instance-bound plugin config store.
83
- * Host stores the validated/interpolated slice per plugin instance.
84
- * The store is intentionally private to this module; definePlugin()
85
- * provides a typed accessor that reads from this store for the calling
86
- * plugin instance.
54
+ * Zod schemas for CLI-facing GetDotenv options (raw/resolved stubs).
55
+ *
56
+ * RAW allows stringly inputs (paths/vars + splitters). RESOLVED will later
57
+ * reflect normalized types (paths: string[], vars: ProcessEnv), applied in the
58
+ * CLI resolution pipeline.
87
59
  */
88
- const PLUGIN_CONFIG_STORE = new WeakMap();
89
- const _getPluginConfigForInstance = (plugin) => PLUGIN_CONFIG_STORE.get(plugin);
60
+ const getDotenvCliOptionsSchemaRaw = getDotenvOptionsSchemaRaw.extend({
61
+ // CLI-specific fields (stringly inputs before preprocessing)
62
+ debug: z.boolean().optional(),
63
+ strict: z.boolean().optional(),
64
+ capture: z.boolean().optional(),
65
+ trace: z.union([z.boolean(), z.array(z.string())]).optional(),
66
+ redact: z.boolean().optional(),
67
+ warnEntropy: z.boolean().optional(),
68
+ entropyThreshold: z.number().optional(),
69
+ entropyMinLength: z.number().optional(),
70
+ entropyWhitelist: z.array(z.string()).optional(),
71
+ redactPatterns: z.array(z.string()).optional(),
72
+ paths: z.string().optional(),
73
+ pathsDelimiter: z.string().optional(),
74
+ pathsDelimiterPattern: z.string().optional(),
75
+ scripts: z.record(z.string(), z.unknown()).optional(),
76
+ shell: z.union([z.boolean(), z.string()]).optional(),
77
+ vars: z.string().optional(),
78
+ varsAssignor: z.string().optional(),
79
+ varsAssignorPattern: z.string().optional(),
80
+ varsDelimiter: z.string().optional(),
81
+ varsDelimiterPattern: z.string().optional(),
82
+ });
90
83
 
91
- /** src/cliHost/definePlugin.ts
92
- * Plugin contracts for the GetDotenv CLI host.
84
+ const visibilityMap = z.record(z.string(), z.boolean());
85
+ /**
86
+ * Zod schemas for configuration files discovered by the new loader.
93
87
  *
94
- * This module exposes a structural public interface for the host that plugins
95
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
96
- * nominal class identity issues (private fields) in downstream consumers.
88
+ * Notes:
89
+ * - RAW: all fields optional; only allowed top-level keys are:
90
+ * - rootOptionDefaults, rootOptionVisibility
91
+ * - scripts, vars, envVars
92
+ * - dynamic (JS/TS only), schema (JS/TS only)
93
+ * - plugins, requiredKeys
94
+ * - RESOLVED: mirrors RAW (no path normalization).
95
+ * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS only).
97
96
  */
98
- /* eslint-disable tsdoc/syntax */
99
- function definePlugin(spec) {
100
- const { children = [], ...rest } = spec;
101
- // Default to a strict empty-object schema so “no-config” plugins fail fast
102
- // on unknown keys and provide a concrete {} at runtime.
103
- const effectiveSchema = spec.configSchema ?? z.object({}).strict();
104
- // Build base plugin first, then extend with instance-bound helpers.
105
- const base = {
106
- ...rest,
107
- // Always carry a schema (strict empty by default) to simplify host logic
108
- // and improve inference/ergonomics for plugin authors.
109
- configSchema: effectiveSchema,
110
- children: [...children],
111
- use(child) {
112
- this.children.push(child);
113
- return this;
114
- },
115
- };
116
- // Attach instance-bound helpers on the returned plugin object.
117
- const extended = base;
118
- extended.readConfig = function (_cli) {
119
- // Config is stored per-plugin-instance by the host (WeakMap in computeContext).
120
- const value = _getPluginConfigForInstance(extended);
121
- if (value === undefined) {
122
- // Guard: host has not resolved config yet (incorrect lifecycle usage).
123
- throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
97
+ // String-only env value map
98
+ const stringMap = z.record(z.string(), z.string());
99
+ const envStringMap = z.record(z.string(), stringMap);
100
+ /**
101
+ * Raw configuration schema for get‑dotenv config files (JSON/YAML/JS/TS).
102
+ * Validates allowed top‑level keys without performing path normalization.
103
+ */
104
+ const getDotenvConfigSchemaRaw = z.object({
105
+ rootOptionDefaults: getDotenvCliOptionsSchemaRaw.optional(),
106
+ rootOptionVisibility: visibilityMap.optional(),
107
+ scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
108
+ requiredKeys: z.array(z.string()).optional(),
109
+ schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
110
+ vars: stringMap.optional(), // public, global
111
+ envVars: envStringMap.optional(), // public, per-env
112
+ // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
113
+ dynamic: z.unknown().optional(),
114
+ // Per-plugin config bag; validated by plugins/host when used.
115
+ plugins: z.record(z.string(), z.unknown()).optional(),
116
+ });
117
+ /**
118
+ * Resolved configuration schema which preserves the raw shape while narrowing
119
+ * the output to {@link GetDotenvConfigResolved}. Consumers get a strongly typed
120
+ * object, while the underlying validation remains Zod‑driven.
121
+ */
122
+ const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => raw);
123
+
124
+ /** @internal */
125
+ const isPlainObject$1 = (value) => value !== null &&
126
+ typeof value === 'object' &&
127
+ Object.getPrototypeOf(value) === Object.prototype;
128
+ const mergeInto = (target, source) => {
129
+ for (const [key, sVal] of Object.entries(source)) {
130
+ if (sVal === undefined)
131
+ continue; // do not overwrite with undefined
132
+ const tVal = target[key];
133
+ if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
134
+ target[key] = mergeInto({ ...tVal }, sVal);
135
+ }
136
+ else if (isPlainObject$1(sVal)) {
137
+ target[key] = mergeInto({}, sVal);
138
+ }
139
+ else {
140
+ target[key] = sVal;
124
141
  }
142
+ }
143
+ return target;
144
+ };
145
+ function defaultsDeep(...layers) {
146
+ const result = layers
147
+ .filter(Boolean)
148
+ .reduce((acc, layer) => mergeInto(acc, layer), {});
149
+ return result;
150
+ }
151
+
152
+ /**
153
+ * Serialize a dotenv record to a file with minimal quoting (multiline values are quoted).
154
+ * Future-proofs for ordering/sorting changes (currently insertion order).
155
+ *
156
+ * @param filename - Destination dotenv file path.
157
+ * @param data - Env-like map of values to write (values may be `undefined`).
158
+ * @returns A `Promise\<void\>` which resolves when the file has been written.
159
+ */
160
+ async function writeDotenvFile(filename, data) {
161
+ // Serialize: key=value with quotes only for multiline values.
162
+ const body = Object.keys(data).reduce((acc, key) => {
163
+ const v = data[key] ?? '';
164
+ const val = v.includes('\n') ? `"${v}"` : v;
165
+ return `${acc}${key}=${val}\n`;
166
+ }, '');
167
+ await fs.writeFile(filename, body, { encoding: 'utf-8' });
168
+ }
169
+
170
+ /**
171
+ * Dotenv expansion utilities.
172
+ *
173
+ * This module implements recursive expansion of environment-variable
174
+ * references in strings and records. It supports both whitespace and
175
+ * bracket syntaxes with optional defaults:
176
+ *
177
+ * - Whitespace: `$VAR[:default]`
178
+ * - Bracketed: `${VAR[:default]}`
179
+ *
180
+ * Escaped dollar signs (`\$`) are preserved.
181
+ * Unknown variables resolve to empty string unless a default is provided.
182
+ */
183
+ /**
184
+ * Like String.prototype.search but returns the last index.
185
+ * @internal
186
+ */
187
+ const searchLast = (str, rgx) => {
188
+ const matches = Array.from(str.matchAll(rgx));
189
+ return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
190
+ };
191
+ const replaceMatch = (value, match, ref) => {
192
+ /**
193
+ * @internal
194
+ */
195
+ const group = match[0];
196
+ const key = match[1];
197
+ const defaultValue = match[2];
198
+ if (!key)
125
199
  return value;
126
- };
127
- // Plugin-bound dynamic option factory
128
- extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
129
- return cli.createDynamicOption(flags, (cfg) => {
130
- // Prefer the validated slice stored per instance; fallback to help-bag
131
- // (by-id) so top-level `-h` can render effective defaults before resolve.
132
- const fromStore = _getPluginConfigForInstance(extended);
133
- const id = extended.id;
134
- let fromBag;
135
- if (!fromStore && id) {
136
- const maybe = cfg.plugins[id];
137
- if (maybe && typeof maybe === 'object') {
138
- fromBag = maybe;
139
- }
200
+ const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
201
+ return interpolate(replacement, ref);
202
+ };
203
+ const interpolate = (value = '', ref = {}) => {
204
+ /**
205
+ * @internal
206
+ */
207
+ // if value is falsy, return it as is
208
+ if (!value)
209
+ return value;
210
+ // get position of last unescaped dollar sign
211
+ const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
212
+ // return value if none found
213
+ if (lastUnescapedDollarSignIndex === -1)
214
+ return value;
215
+ // evaluate the value tail
216
+ const tail = value.slice(lastUnescapedDollarSignIndex);
217
+ // find whitespace pattern: $KEY:DEFAULT
218
+ const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
219
+ const whitespaceMatch = whitespacePattern.exec(tail);
220
+ if (whitespaceMatch != null)
221
+ return replaceMatch(value, whitespaceMatch, ref);
222
+ else {
223
+ // find bracket pattern: ${KEY:DEFAULT}
224
+ const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
225
+ const bracketMatch = bracketPattern.exec(tail);
226
+ if (bracketMatch != null)
227
+ return replaceMatch(value, bracketMatch, ref);
228
+ }
229
+ return value;
230
+ };
231
+ /**
232
+ * Recursively expands environment variables in a string. Variables may be
233
+ * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
234
+ * Unknown variables will expand to an empty string.
235
+ *
236
+ * @param value - The string to expand.
237
+ * @param ref - The reference object to use for variable expansion.
238
+ * @returns The expanded string.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * process.env.FOO = 'bar';
243
+ * dotenvExpand('Hello $FOO'); // "Hello bar"
244
+ * dotenvExpand('Hello $BAZ:world'); // "Hello world"
245
+ * ```
246
+ *
247
+ * @remarks
248
+ * The expansion is recursive. If a referenced variable itself contains
249
+ * references, those will also be expanded until a stable value is reached.
250
+ * Escaped references (e.g. `\$FOO`) are preserved as literals.
251
+ */
252
+ const dotenvExpand = (value, ref = process.env) => {
253
+ const result = interpolate(value, ref);
254
+ return result ? result.replace(/\\\$/g, '$') : undefined;
255
+ };
256
+ /**
257
+ * Recursively expands environment variables in the values of a JSON object.
258
+ * Variables may be presented with optional default as `$VAR[:default]` or
259
+ * `${VAR[:default]}`. Unknown variables will expand to an empty string.
260
+ *
261
+ * @param values - The values object to expand.
262
+ * @param options - Expansion options.
263
+ * @returns The value object with expanded string values.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * process.env.FOO = 'bar';
268
+ * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
269
+ * // => { A: "bar", B: "xbary" }
270
+ * ```
271
+ *
272
+ * @remarks
273
+ * Options:
274
+ * - ref: The reference object to use for expansion (defaults to process.env).
275
+ * - progressive: Whether to progressively add expanded values to the set of
276
+ * reference keys.
277
+ *
278
+ * When `progressive` is true, each expanded key becomes available for
279
+ * subsequent expansions in the same object (left-to-right by object key order).
280
+ */
281
+ function dotenvExpandAll(values, options = {}) {
282
+ const { ref = process.env, progressive = false, } = options;
283
+ const out = Object.keys(values).reduce((acc, key) => {
284
+ acc[key] = dotenvExpand(values[key], {
285
+ ...ref,
286
+ ...(progressive ? acc : {}),
287
+ });
288
+ return acc;
289
+ }, {});
290
+ // Key-preserving return with a permissive index signature to allow later additions.
291
+ return out;
292
+ }
293
+ /**
294
+ * Recursively expands environment variables in a string using `process.env` as
295
+ * the expansion reference. Variables may be presented with optional default as
296
+ * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
297
+ * empty string.
298
+ *
299
+ * @param value - The string to expand.
300
+ * @returns The expanded string.
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * process.env.FOO = 'bar';
305
+ * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
306
+ * ```
307
+ */
308
+ const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
309
+
310
+ /** @internal */
311
+ const isPlainObject = (v) => v !== null &&
312
+ typeof v === 'object' &&
313
+ !Array.isArray(v) &&
314
+ Object.getPrototypeOf(v) === Object.prototype;
315
+ /**
316
+ * Deeply interpolate string leaves against envRef.
317
+ * Arrays are not recursed into; they are returned unchanged.
318
+ *
319
+ * @typeParam T - Shape of the input value.
320
+ * @param value - Input value (object/array/primitive).
321
+ * @param envRef - Reference environment for interpolation.
322
+ * @returns A new value with string leaves interpolated.
323
+ */
324
+ const interpolateDeep = (value, envRef) => {
325
+ // Strings: expand and return
326
+ if (typeof value === 'string') {
327
+ const out = dotenvExpand(value, envRef);
328
+ // dotenvExpand returns string | undefined; preserve original on undefined
329
+ return (out ?? value);
330
+ }
331
+ // Arrays: return as-is (no recursion)
332
+ if (Array.isArray(value)) {
333
+ return value;
334
+ }
335
+ // Plain objects: shallow clone and recurse into values
336
+ if (isPlainObject(value)) {
337
+ const src = value;
338
+ const out = {};
339
+ for (const [k, v] of Object.entries(src)) {
340
+ // Recurse for strings/objects; keep arrays as-is; preserve other scalars
341
+ if (typeof v === 'string')
342
+ out[k] = dotenvExpand(v, envRef) ?? v;
343
+ else if (Array.isArray(v))
344
+ out[k] = v;
345
+ else if (isPlainObject(v))
346
+ out[k] = interpolateDeep(v, envRef);
347
+ else
348
+ out[k] = v;
349
+ }
350
+ return out;
351
+ }
352
+ // Other primitives/types: return as-is
353
+ return value;
354
+ };
355
+
356
+ const importDefault = async (fileUrl) => {
357
+ const mod = (await import(fileUrl));
358
+ return mod.default;
359
+ };
360
+ const cacheHash = (absPath, mtimeMs) => createHash('sha1')
361
+ .update(absPath)
362
+ .update(String(mtimeMs))
363
+ .digest('hex')
364
+ .slice(0, 12);
365
+ /**
366
+ * Remove older compiled cache files for a given source base name, keeping
367
+ * at most `keep` most-recent files. Errors are ignored by design.
368
+ */
369
+ const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
370
+ try {
371
+ const entries = await fs.readdir(cacheDir);
372
+ const mine = entries
373
+ .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
374
+ .map((f) => path.join(cacheDir, f));
375
+ if (mine.length <= keep)
376
+ return;
377
+ const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
378
+ stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
379
+ const toDelete = stats.slice(keep).map((s) => s.p);
380
+ await Promise.all(toDelete.map(async (p) => {
381
+ try {
382
+ await fs.remove(p);
140
383
  }
141
- // Always provide a concrete object to dynamic callbacks:
142
- // - With a schema: computeContext stores the parsed object.
143
- // - Without a schema: computeContext stores {}.
144
- // - Help-time fallback: coalesce to {} when only a by-id bag exists.
145
- const cfgVal = (fromStore ?? fromBag ?? {});
146
- return desc(cfg, cfgVal);
147
- }, parser, defaultValue);
148
- };
149
- return extended;
384
+ catch {
385
+ // best-effort cleanup
386
+ }
387
+ }));
388
+ }
389
+ catch {
390
+ // best-effort cleanup
391
+ }
392
+ };
393
+ /**
394
+ * Load a module default export from a JS/TS file with robust fallbacks.
395
+ *
396
+ * Behavior by extension:
397
+ *
398
+ * - `.js`/`.mjs`/`.cjs`: direct dynamic import.
399
+ * - `.ts`/`.mts`/`.cts`/`.tsx`:
400
+ * - try direct dynamic import (when a TS loader is active),
401
+ * - else compile via `esbuild` to a cached `.mjs` file and import,
402
+ * - else fallback to `typescript.transpileModule` for simple modules.
403
+ *
404
+ * @typeParam T - Type of the expected default export.
405
+ * @param absPath - Absolute path to the source file.
406
+ * @param cacheDirName - Cache subfolder under `.tsbuild/`.
407
+ * @returns A `Promise\<T | undefined\>` resolving to the default export (if any).
408
+ */
409
+ const loadModuleDefault = async (absPath, cacheDirName) => {
410
+ const ext = path.extname(absPath).toLowerCase();
411
+ const fileUrl = url.pathToFileURL(absPath).toString();
412
+ if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
413
+ return importDefault(fileUrl);
414
+ }
415
+ // Try direct import first (TS loader active)
416
+ try {
417
+ const dyn = await importDefault(fileUrl);
418
+ if (dyn)
419
+ return dyn;
420
+ }
421
+ catch {
422
+ /* fall through */
423
+ }
424
+ const stat = await fs.stat(absPath);
425
+ const hash = cacheHash(absPath, stat.mtimeMs);
426
+ const cacheDir = path.resolve('.tsbuild', cacheDirName);
427
+ await fs.ensureDir(cacheDir);
428
+ const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
429
+ // Try esbuild
430
+ try {
431
+ const esbuild = (await import('esbuild'));
432
+ await esbuild.build({
433
+ entryPoints: [absPath],
434
+ bundle: true,
435
+ platform: 'node',
436
+ format: 'esm',
437
+ target: 'node20',
438
+ outfile: cacheFile,
439
+ sourcemap: false,
440
+ logLevel: 'silent',
441
+ });
442
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
443
+ // Best-effort: trim older cache files for this source.
444
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
445
+ return result;
446
+ }
447
+ catch {
448
+ /* fall through to TS transpile */
449
+ }
450
+ // TypeScript transpile fallback
451
+ try {
452
+ const ts = (await import('typescript'));
453
+ const code = await fs.readFile(absPath, 'utf-8');
454
+ const out = ts.transpileModule(code, {
455
+ compilerOptions: {
456
+ module: 'ESNext',
457
+ target: 'ES2022',
458
+ moduleResolution: 'NodeNext',
459
+ },
460
+ }).outputText;
461
+ await fs.writeFile(cacheFile, out, 'utf-8');
462
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
463
+ // Best-effort: trim older cache files for this source.
464
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
465
+ return result;
466
+ }
467
+ catch {
468
+ // Caller decides final error wording; rethrow for upstream mapping.
469
+ throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
470
+ }
471
+ };
472
+
473
+ /** src/util/omitUndefined.ts
474
+ * Helpers to drop undefined-valued properties in a typed-friendly way.
475
+ */
476
+ /**
477
+ * Omit keys whose runtime value is undefined from a shallow object.
478
+ * Returns a Partial with non-undefined value types preserved.
479
+ *
480
+ * @typeParam T - Input object shape.
481
+ * @param obj - Object to filter.
482
+ * @returns A shallow copy of `obj` without keys whose value is `undefined`.
483
+ */
484
+ function omitUndefined(obj) {
485
+ const out = {};
486
+ for (const [k, v] of Object.entries(obj)) {
487
+ if (v !== undefined)
488
+ out[k] = v;
489
+ }
490
+ return out;
491
+ }
492
+ /**
493
+ * Specialized helper for env-like maps: drop undefined and return string-only.
494
+ *
495
+ * @typeParam V - Value type for present entries (must extend `string`).
496
+ * @param obj - Env-like record containing `string | undefined` values.
497
+ * @returns A new record containing only the keys with defined values.
498
+ */
499
+ function omitUndefinedRecord(obj) {
500
+ const out = {};
501
+ for (const [k, v] of Object.entries(obj)) {
502
+ if (v !== undefined)
503
+ out[k] = v;
504
+ }
505
+ return out;
150
506
  }
151
507
 
152
- // Minimal tokenizer for shell-off execution:
153
- // Splits by whitespace while preserving quoted segments (single or double quotes).
154
- // Optionally preserve doubled quotes inside quoted segments:
155
- // - default: "" => " (Windows/PowerShell style literal-quote escape)
156
- // - preserveDoubledQuotes: true => "" stays "" (needed for Node -e payloads)
508
+ /**
509
+ * Minimal tokenizer for shell-off execution.
510
+ * Splits by whitespace while preserving quoted segments (single or double quotes).
511
+ *
512
+ * @param command - The command string to tokenize.
513
+ * @param opts - Tokenization options (e.g. quote handling).
514
+ */
157
515
  const tokenize = (command, opts) => {
158
516
  const out = [];
159
517
  let cur = '';
@@ -182,141 +540,1894 @@ const tokenize = (command, opts) => {
182
540
  cur += c;
183
541
  }
184
542
  }
185
- else {
186
- if (c === '"' || c === "'") {
187
- quote = c;
188
- }
189
- else if (/\s/.test(c)) {
190
- if (cur) {
191
- out.push(cur);
192
- cur = '';
193
- }
194
- }
195
- else {
196
- cur += c;
543
+ else {
544
+ if (c === '"' || c === "'") {
545
+ quote = c;
546
+ }
547
+ else if (/\s/.test(c)) {
548
+ if (cur) {
549
+ out.push(cur);
550
+ cur = '';
551
+ }
552
+ }
553
+ else {
554
+ cur += c;
555
+ }
556
+ }
557
+ }
558
+ if (cur)
559
+ out.push(cur);
560
+ return out;
561
+ };
562
+
563
+ /**
564
+ * @packageDocumentation
565
+ * Configuration discovery and loading for get‑dotenv. Discovers config files
566
+ * in the packaged root and project root, loads JSON/YAML/JS/TS documents, and
567
+ * validates them against Zod schemas.
568
+ */
569
+ // Discovery candidates (first match wins per scope/privacy).
570
+ // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
571
+ const PUBLIC_FILENAMES = [
572
+ 'getdotenv.config.json',
573
+ 'getdotenv.config.yaml',
574
+ 'getdotenv.config.yml',
575
+ 'getdotenv.config.js',
576
+ 'getdotenv.config.mjs',
577
+ 'getdotenv.config.cjs',
578
+ 'getdotenv.config.ts',
579
+ 'getdotenv.config.mts',
580
+ 'getdotenv.config.cts',
581
+ ];
582
+ const LOCAL_FILENAMES = [
583
+ 'getdotenv.config.local.json',
584
+ 'getdotenv.config.local.yaml',
585
+ 'getdotenv.config.local.yml',
586
+ 'getdotenv.config.local.js',
587
+ 'getdotenv.config.local.mjs',
588
+ 'getdotenv.config.local.cjs',
589
+ 'getdotenv.config.local.ts',
590
+ 'getdotenv.config.local.mts',
591
+ 'getdotenv.config.local.cts',
592
+ ];
593
+ const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
594
+ const isJson = (p) => extname(p).toLowerCase() === '.json';
595
+ const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
596
+ /**
597
+ * Discover JSON/YAML config files in the packaged root and project root.
598
+ * Order: packaged public → project public → project local. */
599
+ const discoverConfigFiles = async (importMetaUrl) => {
600
+ const files = [];
601
+ // Packaged root via importMetaUrl (optional)
602
+ if (importMetaUrl) {
603
+ const fromUrl = fileURLToPath(importMetaUrl);
604
+ const packagedRoot = await packageDirectory({ cwd: fromUrl });
605
+ if (packagedRoot) {
606
+ for (const name of PUBLIC_FILENAMES) {
607
+ const p = join(packagedRoot, name);
608
+ if (await fs.pathExists(p)) {
609
+ files.push({ path: p, privacy: 'public', scope: 'packaged' });
610
+ break; // only one public file expected per scope
611
+ }
612
+ }
613
+ // By policy, packaged .local is not expected; skip even if present.
614
+ }
615
+ }
616
+ // Project root (from current working directory)
617
+ const projectRoot = await packageDirectory();
618
+ if (projectRoot) {
619
+ for (const name of PUBLIC_FILENAMES) {
620
+ const p = join(projectRoot, name);
621
+ if (await fs.pathExists(p)) {
622
+ files.push({ path: p, privacy: 'public', scope: 'project' });
623
+ break;
624
+ }
625
+ }
626
+ for (const name of LOCAL_FILENAMES) {
627
+ const p = join(projectRoot, name);
628
+ if (await fs.pathExists(p)) {
629
+ files.push({ path: p, privacy: 'local', scope: 'project' });
630
+ break;
631
+ }
632
+ }
633
+ }
634
+ return files;
635
+ };
636
+ /**
637
+ * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
638
+ * Validates with Zod RAW schema, then normalizes to RESOLVED.
639
+ *
640
+ * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
641
+ * For JS/TS: default export is loaded; "dynamic" is allowed.
642
+ */
643
+ const loadConfigFile = async (filePath) => {
644
+ let raw = {};
645
+ try {
646
+ const abs = path.resolve(filePath);
647
+ if (isJsOrTs(abs)) {
648
+ // JS/TS support: load default export via shared robust pipeline.
649
+ const mod = await loadModuleDefault(abs, 'getdotenv-config');
650
+ raw = mod ?? {};
651
+ }
652
+ else {
653
+ const txt = await fs.readFile(abs, 'utf-8');
654
+ raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
655
+ }
656
+ }
657
+ catch (err) {
658
+ throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
659
+ }
660
+ // Validate RAW
661
+ const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
662
+ if (!parsed.success) {
663
+ const msgs = parsed.error.issues
664
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
665
+ .join('\n');
666
+ throw new Error(`Invalid config ${filePath}:\n${msgs}`);
667
+ }
668
+ // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
669
+ if (!isJsOrTs(filePath) &&
670
+ (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
671
+ throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
672
+ `Use JS/TS config for "dynamic" or "schema".`);
673
+ }
674
+ return getDotenvConfigSchemaResolved.parse(parsed.data);
675
+ };
676
+ /**
677
+ * Discover and load configs into resolved shapes, ordered by scope/privacy.
678
+ * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
679
+ */
680
+ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
681
+ const discovered = await discoverConfigFiles(importMetaUrl);
682
+ const result = {};
683
+ for (const f of discovered) {
684
+ const cfg = await loadConfigFile(f.path);
685
+ if (f.scope === 'packaged') {
686
+ // packaged public only
687
+ result.packaged = cfg;
688
+ }
689
+ else {
690
+ result.project ??= {};
691
+ if (f.privacy === 'public')
692
+ result.project.public = cfg;
693
+ else
694
+ result.project.local = cfg;
695
+ }
696
+ }
697
+ return result;
698
+ };
699
+
700
+ /** src/env/dynamic.ts
701
+ * Helpers for applying and loading dynamic variables (JS/TS).
702
+ *
703
+ * Requirements addressed:
704
+ * - Single service to apply a dynamic map progressively.
705
+ * - Single service to load a JS/TS dynamic module with robust fallbacks (util/loadModuleDefault).
706
+ * - Unify error messaging so callers show consistent guidance.
707
+ */
708
+ /**
709
+ * Apply a dynamic map to the target progressively.
710
+ * - Functions receive (target, env) and may return string | undefined.
711
+ * - Literals are assigned directly (including undefined).
712
+ *
713
+ * @param target - Mutable target environment to assign into.
714
+ * @param map - Dynamic map to apply (functions and/or literal values).
715
+ * @param env - Selected environment name (if any) passed through to dynamic functions.
716
+ * @returns Nothing.
717
+ */
718
+ function applyDynamicMap(target, map, env) {
719
+ if (!map)
720
+ return;
721
+ for (const key of Object.keys(map)) {
722
+ const val = typeof map[key] === 'function'
723
+ ? map[key](target, env)
724
+ : map[key];
725
+ Object.assign(target, { [key]: val });
726
+ }
727
+ }
728
+ /**
729
+ * Load a default-export dynamic map from a JS/TS file and apply it.
730
+ * Uses util/loadModuleDefault for robust TS handling (direct import, esbuild,
731
+ * typescript.transpile fallback).
732
+ *
733
+ * Error behavior:
734
+ * - On failure to load/compile/evaluate the module, throws a unified message:
735
+ * "Unable to load dynamic TypeScript file: <absPath>. Install 'esbuild'..."
736
+ *
737
+ * @param target - Mutable target environment to assign into.
738
+ * @param absPath - Absolute path to the dynamic module file.
739
+ * @param env - Selected environment name (if any).
740
+ * @param cacheDirName - Cache subdirectory under `.tsbuild/` for compiled artifacts.
741
+ * @returns A `Promise\<void\>` which resolves after the module (if present) has been applied.
742
+ */
743
+ async function loadAndApplyDynamic(target, absPath, env, cacheDirName) {
744
+ if (!(await fs.exists(absPath)))
745
+ return;
746
+ let dyn;
747
+ try {
748
+ dyn = await loadModuleDefault(absPath, cacheDirName);
749
+ }
750
+ catch {
751
+ // Preserve legacy/clear guidance used by tests and docs.
752
+ throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
753
+ `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
754
+ }
755
+ applyDynamicMap(target, dyn, env);
756
+ }
757
+
758
+ const applyKv = (current, kv) => {
759
+ if (!kv || Object.keys(kv).length === 0)
760
+ return current;
761
+ const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
762
+ return { ...current, ...expanded };
763
+ };
764
+ const applyConfigSlice = (current, cfg, env) => {
765
+ if (!cfg)
766
+ return current;
767
+ // kind axis: global then env (env overrides global)
768
+ const afterGlobal = applyKv(current, cfg.vars);
769
+ const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
770
+ return applyKv(afterGlobal, envKv);
771
+ };
772
+ function overlayEnv(args) {
773
+ const { base, env, configs } = args;
774
+ let current = { ...base };
775
+ // Source: packaged (public -> local)
776
+ current = applyConfigSlice(current, configs.packaged, env);
777
+ // Packaged "local" is not expected by policy; if present, honor it.
778
+ // We do not have a separate object for packaged.local in sources, keep as-is.
779
+ // Source: project (public -> local)
780
+ current = applyConfigSlice(current, configs.project?.public, env);
781
+ current = applyConfigSlice(current, configs.project?.local, env);
782
+ // Programmatic explicit vars (top of static tier)
783
+ if ('programmaticVars' in args) {
784
+ const toApply = Object.fromEntries(Object.entries(args.programmaticVars).filter(([_k, v]) => typeof v === 'string'));
785
+ current = applyKv(current, toApply);
786
+ }
787
+ return current;
788
+ }
789
+
790
+ /** src/diagnostics/entropy.ts
791
+ * Entropy diagnostics (presentation-only).
792
+ * - Gated by min length and printable ASCII.
793
+ * - Warn once per key per run when bits/char \>= threshold.
794
+ * - Supports whitelist patterns to suppress known-noise keys.
795
+ */
796
+ const warned = new Set();
797
+ const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
798
+ const compile$1 = (patterns) => (patterns ?? []).map((p) => (typeof p === 'string' ? new RegExp(p, 'i') : p));
799
+ const whitelisted = (key, regs) => regs.some((re) => re.test(key));
800
+ const shannonBitsPerChar = (s) => {
801
+ const freq = new Map();
802
+ for (const ch of s)
803
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
804
+ const n = s.length;
805
+ let h = 0;
806
+ for (const c of freq.values()) {
807
+ const p = c / n;
808
+ h -= p * Math.log2(p);
809
+ }
810
+ return h;
811
+ };
812
+ /**
813
+ * Maybe emit a one-line entropy warning for a key.
814
+ * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
815
+ */
816
+ const maybeWarnEntropy = (key, value, origin, opts, emit) => {
817
+ if (!opts || opts.warnEntropy === false)
818
+ return;
819
+ if (warned.has(key))
820
+ return;
821
+ const v = value ?? '';
822
+ const minLen = Math.max(0, opts.entropyMinLength ?? 16);
823
+ const threshold = opts.entropyThreshold ?? 3.8;
824
+ if (v.length < minLen)
825
+ return;
826
+ if (!isPrintableAscii(v))
827
+ return;
828
+ const wl = compile$1(opts.entropyWhitelist);
829
+ if (whitelisted(key, wl))
830
+ return;
831
+ const bpc = shannonBitsPerChar(v);
832
+ if (bpc >= threshold) {
833
+ warned.add(key);
834
+ emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
835
+ }
836
+ };
837
+
838
+ const DEFAULT_PATTERNS = [
839
+ '\\bsecret\\b',
840
+ '\\btoken\\b',
841
+ '\\bpass(word)?\\b',
842
+ '\\bapi[_-]?key\\b',
843
+ '\\bkey\\b',
844
+ ];
845
+ const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => typeof p === 'string' ? new RegExp(p, 'i') : p);
846
+ const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
847
+ const MASK = '[redacted]';
848
+ /**
849
+ * Produce a shallow redacted copy of an env-like object for display.
850
+ */
851
+ const redactObject = (obj, opts) => {
852
+ if (!opts?.redact)
853
+ return { ...obj };
854
+ const regs = compile(opts.redactPatterns);
855
+ const out = {};
856
+ for (const [k, v] of Object.entries(obj)) {
857
+ out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
858
+ }
859
+ return out;
860
+ };
861
+
862
+ /**
863
+ * Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
864
+ * Used as the bottom layer for CLI option resolution.
865
+ */
866
+ /**
867
+ * Default values for root CLI options used by the host and helpers as the
868
+ * baseline layer during option resolution.
869
+ *
870
+ * These defaults correspond to the "stringly" root surface (see `RootOptionsShape`)
871
+ * and are merged by precedence with create-time overrides and any discovered
872
+ * configuration `rootOptionDefaults` before CLI flags are applied.
873
+ */
874
+ const baseRootOptionDefaults = {
875
+ dotenvToken: '.env',
876
+ loadProcess: true,
877
+ logger: console,
878
+ // Diagnostics defaults
879
+ warnEntropy: true,
880
+ entropyThreshold: 3.8,
881
+ entropyMinLength: 16,
882
+ entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
883
+ paths: './',
884
+ pathsDelimiter: ' ',
885
+ privateToken: 'local',
886
+ scripts: {
887
+ 'git-status': {
888
+ cmd: 'git branch --show-current && git status -s -u',
889
+ shell: true,
890
+ },
891
+ },
892
+ shell: true,
893
+ vars: '',
894
+ varsAssignor: '=',
895
+ varsDelimiter: ' ',
896
+ // tri-state flags default to unset unless explicitly provided
897
+ // (debug/log/exclude* resolved via flag utils)
898
+ };
899
+
900
+ /**
901
+ * Converts programmatic CLI options to `getDotenv` options.
902
+ *
903
+ * Accepts "stringly" CLI inputs for vars/paths and normalizes them into
904
+ * the programmatic shape. Preserves exactOptionalPropertyTypes semantics by
905
+ * omitting keys when undefined.
906
+ */
907
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern,
908
+ // drop CLI-only keys from the pass-through bag
909
+ debug: _debug, scripts: _scripts, ...rest }) => {
910
+ // Split helper for delimited strings or regex patterns
911
+ const splitBy = (value, delim, pattern) => {
912
+ if (!value)
913
+ return [];
914
+ if (pattern)
915
+ return value.split(RegExp(pattern));
916
+ if (typeof delim === 'string')
917
+ return value.split(delim);
918
+ return value.split(' ');
919
+ };
920
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
921
+ let parsedVars;
922
+ if (typeof vars === 'string') {
923
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern)
924
+ .map((v) => v.split(varsAssignorPattern
925
+ ? RegExp(varsAssignorPattern)
926
+ : (varsAssignor ?? '=')))
927
+ .filter(([k]) => typeof k === 'string' && k.length > 0);
928
+ parsedVars = Object.fromEntries(kvPairs);
929
+ }
930
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
931
+ // Accept provided object map of string | undefined; drop undefined values
932
+ // in the normalization step below to produce a ProcessEnv-compatible bag.
933
+ parsedVars = Object.fromEntries(Object.entries(vars));
934
+ }
935
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
936
+ // expectations and the compat test assertions.
937
+ if (parsedVars) {
938
+ parsedVars = omitUndefinedRecord(parsedVars);
939
+ }
940
+ // Tolerate paths as either a delimited string or string[]
941
+ const pathsOut = Array.isArray(paths)
942
+ ? paths.filter((p) => typeof p === 'string')
943
+ : splitBy(paths, pathsDelimiter, pathsDelimiterPattern);
944
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
945
+ return {
946
+ // Ensure the required logger property is present. The base CLI defaults
947
+ // specify console as the logger; callers can override upstream if desired.
948
+ logger: console,
949
+ ...rest,
950
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
951
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
952
+ };
953
+ };
954
+ /**
955
+ * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
956
+ *
957
+ * 1. Base defaults derived from the CLI generator defaults
958
+ * ({@link baseGetDotenvCliOptions}).
959
+ * 2. Local project overrides from a `getdotenv.config.json` in the nearest
960
+ * package root (if present).
961
+ * 3. The provided customOptions.
962
+ *
963
+ * The result preserves explicit empty values and drops only `undefined`.
964
+ */
965
+ const resolveGetDotenvOptions = (customOptions) => {
966
+ // Programmatic callers use neutral defaults only. Do not read local packaged
967
+ // getdotenv.config.json here; the host path applies packaged/project configs
968
+ // via the dedicated loader/overlay pipeline.
969
+ const mergedDefaults = baseRootOptionDefaults;
970
+ const defaultsFromCli = getDotenvCliOptions2Options(mergedDefaults);
971
+ const result = defaultsDeep(defaultsFromCli, customOptions);
972
+ return Promise.resolve({
973
+ ...result, // Keep explicit empty strings/zeros; drop only undefined
974
+ vars: omitUndefinedRecord(result.vars ?? {}),
975
+ });
976
+ };
977
+
978
+ /**
979
+ * Asynchronously read a dotenv file & parse it into an object.
980
+ *
981
+ * @param path - Path to dotenv file.
982
+ * @returns The parsed dotenv object.
983
+ */
984
+ const readDotenv = async (path) => {
985
+ try {
986
+ return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
987
+ }
988
+ catch {
989
+ return {};
990
+ }
991
+ };
992
+
993
+ async function getDotenv(options = {}) {
994
+ // Apply defaults.
995
+ const { defaultEnv, dotenvToken = '.env', dynamicPath, env, excludeDynamic = false, excludeEnv = false, excludeGlobal = false, excludePrivate = false, excludePublic = false, loadProcess = false, log = false, logger = console, outputPath, paths = [], privateToken = 'local', vars = {}, } = await resolveGetDotenvOptions(options);
996
+ // Read .env files.
997
+ const loaded = paths.length
998
+ ? await paths.reduce(async (e, p) => {
999
+ const publicGlobal = excludePublic || excludeGlobal
1000
+ ? Promise.resolve({})
1001
+ : readDotenv(path.resolve(p, dotenvToken));
1002
+ const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1003
+ ? Promise.resolve({})
1004
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1005
+ const privateGlobal = excludePrivate || excludeGlobal
1006
+ ? Promise.resolve({})
1007
+ : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1008
+ const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1009
+ ? Promise.resolve({})
1010
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1011
+ const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1012
+ e,
1013
+ publicGlobal,
1014
+ publicEnv,
1015
+ privateGlobal,
1016
+ privateEnv,
1017
+ ]);
1018
+ return {
1019
+ ...eResolved,
1020
+ ...publicGlobalResolved,
1021
+ ...publicEnvResolved,
1022
+ ...privateGlobalResolved,
1023
+ ...privateEnvResolved,
1024
+ };
1025
+ }, Promise.resolve({}))
1026
+ : {};
1027
+ const outputKey = nanoid();
1028
+ const dotenv = dotenvExpandAll({
1029
+ ...loaded,
1030
+ ...vars,
1031
+ ...(outputPath ? { [outputKey]: outputPath } : {}),
1032
+ }, { progressive: true });
1033
+ // Process dynamic variables. Programmatic option takes precedence over path.
1034
+ if (!excludeDynamic) {
1035
+ let dynamic = undefined;
1036
+ if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1037
+ dynamic = options.dynamic;
1038
+ }
1039
+ else if (dynamicPath) {
1040
+ const absDynamicPath = path.resolve(dynamicPath);
1041
+ await loadAndApplyDynamic(dotenv, absDynamicPath, env ?? defaultEnv, 'getdotenv-dynamic');
1042
+ }
1043
+ if (dynamic) {
1044
+ try {
1045
+ applyDynamicMap(dotenv, dynamic, env ?? defaultEnv);
1046
+ }
1047
+ catch {
1048
+ throw new Error(`Unable to evaluate dynamic variables.`);
1049
+ }
1050
+ }
1051
+ }
1052
+ // Write output file.
1053
+ let resultDotenv = dotenv;
1054
+ if (outputPath) {
1055
+ const outputPathResolved = dotenv[outputKey];
1056
+ if (!outputPathResolved)
1057
+ throw new Error('Output path not found.');
1058
+ const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1059
+ await writeDotenvFile(outputPathResolved, dotenvForOutput);
1060
+ resultDotenv = dotenvForOutput;
1061
+ }
1062
+ // Log result.
1063
+ if (log) {
1064
+ const redactFlag = options.redact ?? false;
1065
+ const redactPatterns = options.redactPatterns ?? undefined;
1066
+ const redOpts = {};
1067
+ if (redactFlag)
1068
+ redOpts.redact = true;
1069
+ if (redactFlag && Array.isArray(redactPatterns))
1070
+ redOpts.redactPatterns = redactPatterns;
1071
+ const bag = redactFlag
1072
+ ? redactObject(resultDotenv, redOpts)
1073
+ : { ...resultDotenv };
1074
+ logger.log(bag);
1075
+ // Entropy warnings: once-per-key-per-run (presentation only)
1076
+ const warnEntropyVal = options.warnEntropy ?? true;
1077
+ const entropyThresholdVal = options
1078
+ .entropyThreshold;
1079
+ const entropyMinLengthVal = options
1080
+ .entropyMinLength;
1081
+ const entropyWhitelistVal = options.entropyWhitelist;
1082
+ const entOpts = {};
1083
+ if (typeof warnEntropyVal === 'boolean')
1084
+ entOpts.warnEntropy = warnEntropyVal;
1085
+ if (typeof entropyThresholdVal === 'number')
1086
+ entOpts.entropyThreshold = entropyThresholdVal;
1087
+ if (typeof entropyMinLengthVal === 'number')
1088
+ entOpts.entropyMinLength = entropyMinLengthVal;
1089
+ if (Array.isArray(entropyWhitelistVal))
1090
+ entOpts.entropyWhitelist = entropyWhitelistVal;
1091
+ for (const [k, v] of Object.entries(resultDotenv)) {
1092
+ maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1093
+ logger.log(line);
1094
+ });
1095
+ }
1096
+ }
1097
+ // Load process.env.
1098
+ if (loadProcess)
1099
+ Object.assign(process.env, resultDotenv);
1100
+ return resultDotenv;
1101
+ }
1102
+
1103
+ /**
1104
+ * Compute the realized path for a command mount (leaf-up to root).
1105
+ * Excludes the root application alias.
1106
+ *
1107
+ * @param cli - The mounted command instance.
1108
+ */
1109
+ /**
1110
+ * Flatten a plugin tree into a list of `{ plugin, path }` entries.
1111
+ * Traverses the namespace chain in pre-order.
1112
+ */
1113
+ function flattenPluginTreeByPath(plugins, prefix) {
1114
+ const out = [];
1115
+ for (const p of plugins) {
1116
+ const here = prefix && prefix.length > 0 ? `${prefix}/${p.ns}` : p.ns;
1117
+ out.push({ plugin: p, path: here });
1118
+ if (Array.isArray(p.children) && p.children.length > 0) {
1119
+ out.push(...flattenPluginTreeByPath(p.children.map((c) => c.plugin), here));
1120
+ }
1121
+ }
1122
+ return out;
1123
+ }
1124
+
1125
+ /**
1126
+ * Instance-bound plugin config store.
1127
+ * Host stores the validated/interpolated slice per plugin instance.
1128
+ * The store is intentionally private to this module; definePlugin()
1129
+ * provides a typed accessor that reads from this store for the calling
1130
+ * plugin instance.
1131
+ */
1132
+ const PLUGIN_CONFIG_STORE = new WeakMap();
1133
+ /**
1134
+ * Store a validated, interpolated config slice for a specific plugin instance.
1135
+ * Generic on both the host options type and the plugin config type to avoid
1136
+ * defaulting to GetDotenvOptions under exactOptionalPropertyTypes.
1137
+ */
1138
+ const setPluginConfig = (plugin, cfg) => {
1139
+ PLUGIN_CONFIG_STORE.set(plugin, cfg);
1140
+ };
1141
+ /**
1142
+ * Retrieve the validated/interpolated config slice for a plugin instance.
1143
+ */
1144
+ const getPluginConfig = (plugin) => {
1145
+ return PLUGIN_CONFIG_STORE.get(plugin);
1146
+ };
1147
+ /**
1148
+ * Compute the dotenv context for the host (uses the config loader/overlay path).
1149
+ * - Resolves and validates options strictly (host-only).
1150
+ * - Applies file cascade, overlays, dynamics, and optional effects.
1151
+ * - Merges and validates per-plugin config slices (when provided), keyed by
1152
+ * realized mount path (ns chain).
1153
+ *
1154
+ * @param customOptions - Partial options from the current invocation.
1155
+ * @param plugins - Installed plugins (for config validation).
1156
+ * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery).
1157
+ */
1158
+ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1159
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
1160
+ // Zod boundary: parse returns the schema-derived shape; we adopt our public
1161
+ // GetDotenvOptions overlay (logger/dynamic typing) for internal processing.
1162
+ const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1163
+ // Build a pure base without side effects or logging (no dynamics, no programmatic vars).
1164
+ const cleanedValidated = omitUndefined(validated);
1165
+ const base = await getDotenv({
1166
+ ...cleanedValidated,
1167
+ excludeDynamic: true,
1168
+ vars: {},
1169
+ log: false,
1170
+ loadProcess: false,
1171
+ });
1172
+ // Discover config sources and overlay with progressive expansion per slice.
1173
+ const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1174
+ const dotenvOverlaid = overlayEnv({
1175
+ base,
1176
+ env: validated.env ?? validated.defaultEnv,
1177
+ configs: sources,
1178
+ ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1179
+ });
1180
+ const dotenv = { ...dotenvOverlaid };
1181
+ // Programmatic dynamic variables (when provided)
1182
+ applyDynamicMap(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1183
+ // Packaged/project dynamics
1184
+ const packagedDyn = (sources.packaged?.dynamic ?? undefined);
1185
+ const publicDyn = (sources.project?.public?.dynamic ?? undefined);
1186
+ const localDyn = (sources.project?.local?.dynamic ?? undefined);
1187
+ applyDynamicMap(dotenv, packagedDyn, validated.env ?? validated.defaultEnv);
1188
+ applyDynamicMap(dotenv, publicDyn, validated.env ?? validated.defaultEnv);
1189
+ applyDynamicMap(dotenv, localDyn, validated.env ?? validated.defaultEnv);
1190
+ // file dynamicPath (lowest)
1191
+ if (validated.dynamicPath) {
1192
+ const absDynamicPath = path.resolve(validated.dynamicPath);
1193
+ await loadAndApplyDynamic(dotenv, absDynamicPath, validated.env ?? validated.defaultEnv, 'getdotenv-dynamic-host');
1194
+ }
1195
+ // Effects:
1196
+ if (validated.outputPath) {
1197
+ await writeDotenvFile(validated.outputPath, dotenv);
1198
+ }
1199
+ const logger = validated.logger;
1200
+ if (validated.log)
1201
+ logger.log(dotenv);
1202
+ if (validated.loadProcess)
1203
+ Object.assign(process.env, dotenv);
1204
+ // Merge and validate per-plugin config keyed by realized path (ns chain).
1205
+ const packagedPlugins = (sources.packaged &&
1206
+ sources.packaged.plugins) ??
1207
+ {};
1208
+ const publicPlugins = (sources.project?.public &&
1209
+ sources.project.public.plugins) ??
1210
+ {};
1211
+ const localPlugins = (sources.project?.local &&
1212
+ sources.project.local.plugins) ??
1213
+ {};
1214
+ const entries = flattenPluginTreeByPath(plugins);
1215
+ const mergedPluginConfigsByPath = {};
1216
+ const envRef = {
1217
+ ...dotenv,
1218
+ ...process.env,
1219
+ };
1220
+ for (const e of entries) {
1221
+ const pathKey = e.path;
1222
+ const mergedRaw = defaultsDeep({}, packagedPlugins[pathKey] ?? {}, publicPlugins[pathKey] ?? {}, localPlugins[pathKey] ?? {});
1223
+ const interpolated = mergedRaw && typeof mergedRaw === 'object'
1224
+ ? interpolateDeep(mergedRaw, envRef)
1225
+ : {};
1226
+ const schema = e.plugin.configSchema;
1227
+ if (schema) {
1228
+ const parsed = schema.safeParse(interpolated);
1229
+ if (!parsed.success) {
1230
+ const err = parsed.error;
1231
+ const msgs = err.issues
1232
+ .map((i) => {
1233
+ const pth = Array.isArray(i.path) ? i.path.join('.') : '';
1234
+ const msg = typeof i.message === 'string' ? i.message : 'Invalid value';
1235
+ return pth ? `${pth}: ${msg}` : msg;
1236
+ })
1237
+ .join('\n');
1238
+ throw new Error(`Invalid config for plugin at '${pathKey}':\n${msgs}`);
1239
+ }
1240
+ const frozen = Object.freeze(parsed.data);
1241
+ setPluginConfig(e.plugin, frozen);
1242
+ mergedPluginConfigsByPath[pathKey] = frozen;
1243
+ }
1244
+ else {
1245
+ const frozen = Object.freeze(interpolated);
1246
+ setPluginConfig(e.plugin, frozen);
1247
+ mergedPluginConfigsByPath[pathKey] = frozen;
1248
+ }
1249
+ }
1250
+ return {
1251
+ optionsResolved: validated,
1252
+ dotenv,
1253
+ plugins: {},
1254
+ pluginConfigs: mergedPluginConfigsByPath,
1255
+ };
1256
+ };
1257
+
1258
+ // Implementation
1259
+ function definePlugin(spec) {
1260
+ const { ...rest } = spec;
1261
+ const effectiveSchema = spec.configSchema ?? z.object({}).strict();
1262
+ const base = {
1263
+ ...rest,
1264
+ configSchema: effectiveSchema,
1265
+ children: [],
1266
+ use(child, override) {
1267
+ // Enforce sibling uniqueness at composition time.
1268
+ const desired = (override && typeof override.ns === 'string' && override.ns.length > 0
1269
+ ? override.ns
1270
+ : child.ns).trim();
1271
+ const collision = this.children.some((c) => {
1272
+ const ns = (c.override &&
1273
+ typeof c.override.ns === 'string' &&
1274
+ c.override.ns.length > 0
1275
+ ? c.override.ns
1276
+ : c.plugin.ns).trim();
1277
+ return ns === desired;
1278
+ });
1279
+ if (collision) {
1280
+ const under = this.ns && this.ns.length > 0 ? this.ns : 'root';
1281
+ throw new Error(`Duplicate namespace '${desired}' under '${under}'. ` +
1282
+ `Override via .use(plugin, { ns: '...' }).`);
1283
+ }
1284
+ this.children.push({ plugin: child, override });
1285
+ return this;
1286
+ },
1287
+ };
1288
+ const extended = base;
1289
+ extended.readConfig = function (_cli) {
1290
+ const value = getPluginConfig(extended);
1291
+ if (value === undefined) {
1292
+ throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
1293
+ }
1294
+ return value;
1295
+ };
1296
+ extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
1297
+ // Derive realized path strictly from the provided mount (leaf-up).
1298
+ const realizedPath = (() => {
1299
+ const parts = [];
1300
+ let node = cli;
1301
+ while (node.parent) {
1302
+ parts.push(node.name());
1303
+ node = node.parent;
1304
+ }
1305
+ return parts.reverse().join('/');
1306
+ })();
1307
+ return cli.createDynamicOption(flags, (c) => {
1308
+ const fromStore = getPluginConfig(extended);
1309
+ let cfgVal = fromStore ?? {};
1310
+ // Strict fallback only by realized path for help-time synthetic usage.
1311
+ if (!fromStore && realizedPath.length > 0) {
1312
+ const bag = c.plugins;
1313
+ const maybe = bag[realizedPath];
1314
+ if (maybe && typeof maybe === 'object') {
1315
+ cfgVal = maybe;
1316
+ }
1317
+ }
1318
+ // c is strictly typed as ResolvedHelpConfig from cli.createDynamicOption
1319
+ return desc(c, cfgVal);
1320
+ }, parser, defaultValue);
1321
+ };
1322
+ return extended;
1323
+ }
1324
+
1325
+ const dbg = (...args) => {
1326
+ if (process.env.GETDOTENV_DEBUG) {
1327
+ // Use stderr to avoid interfering with stdout assertions
1328
+ console.error('[getdotenv:run]', ...args);
1329
+ }
1330
+ };
1331
+ // Strip repeated symmetric outer quotes (single or double) until stable.
1332
+ // This is safe for argv arrays passed to execa (no quoting needed) and avoids
1333
+ // passing quote characters through to Node (e.g., for `node -e "<code>"`).
1334
+ // Handles stacked quotes from shells like PowerShell: """code""" -> code.
1335
+ const stripOuterQuotes = (s) => {
1336
+ let out = s;
1337
+ // Repeatedly trim only when the entire string is wrapped in matching quotes.
1338
+ // Stop as soon as the ends are asymmetric or no quotes remain.
1339
+ while (out.length >= 2) {
1340
+ const a = out.charAt(0);
1341
+ const b = out.charAt(out.length - 1);
1342
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
1343
+ if (!symmetric)
1344
+ break;
1345
+ out = out.slice(1, -1);
1346
+ }
1347
+ return out;
1348
+ };
1349
+ // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
1350
+ const pickResult = (r) => {
1351
+ const exit = r.exitCode;
1352
+ const stdoutVal = r.stdout;
1353
+ const stderrVal = r.stderr;
1354
+ return {
1355
+ exitCode: typeof exit === 'number' ? exit : Number.NaN,
1356
+ stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
1357
+ stderr: typeof stderrVal === 'string' ? stderrVal : '',
1358
+ };
1359
+ };
1360
+ // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
1361
+ // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
1362
+ const sanitizeEnv = (env) => {
1363
+ if (!env)
1364
+ return undefined;
1365
+ const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
1366
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
1367
+ };
1368
+ /**
1369
+ * Core executor that normalizes shell/plain forms and capture/inherit modes.
1370
+ * Returns captured buffers; callers may stream stdout when desired.
1371
+ */
1372
+ async function _execNormalized(command, shell, opts = {}) {
1373
+ const envSan = sanitizeEnv(opts.env);
1374
+ const timeoutBits = typeof opts.timeoutMs === 'number'
1375
+ ? { timeout: opts.timeoutMs, killSignal: 'SIGKILL' }
1376
+ : {};
1377
+ const stdio = opts.stdio ?? 'pipe';
1378
+ if (shell === false) {
1379
+ let file;
1380
+ let args = [];
1381
+ if (typeof command === 'string') {
1382
+ const tokens = tokenize(command);
1383
+ file = tokens[0];
1384
+ args = tokens.slice(1);
1385
+ }
1386
+ else {
1387
+ file = command[0];
1388
+ args = command.slice(1).map(stripOuterQuotes);
1389
+ }
1390
+ if (!file)
1391
+ return { exitCode: 0, stdout: '', stderr: '' };
1392
+ dbg('exec (plain)', { file, args, stdio });
1393
+ try {
1394
+ const ok = pickResult((await execa(file, args, {
1395
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
1396
+ ...(envSan !== undefined ? { env: envSan } : {}),
1397
+ stdio,
1398
+ ...timeoutBits,
1399
+ })));
1400
+ dbg('exit (plain)', { exitCode: ok.exitCode });
1401
+ return ok;
1402
+ }
1403
+ catch (e) {
1404
+ const out = pickResult(e);
1405
+ dbg('exit:error (plain)', { exitCode: out.exitCode });
1406
+ return out;
1407
+ }
1408
+ }
1409
+ // Shell path (string|true|URL): execaCommand handles shell resolution.
1410
+ const commandStr = typeof command === 'string' ? command : command.join(' ');
1411
+ dbg('exec (shell)', {
1412
+ command: commandStr,
1413
+ shell: typeof shell === 'string' ? shell : 'custom',
1414
+ stdio,
1415
+ });
1416
+ try {
1417
+ const ok = pickResult((await execaCommand(commandStr, {
1418
+ shell,
1419
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
1420
+ ...(envSan !== undefined ? { env: envSan } : {}),
1421
+ stdio,
1422
+ ...timeoutBits,
1423
+ })));
1424
+ dbg('exit (shell)', { exitCode: ok.exitCode });
1425
+ return ok;
1426
+ }
1427
+ catch (e) {
1428
+ const out = pickResult(e);
1429
+ dbg('exit:error (shell)', { exitCode: out.exitCode });
1430
+ return out;
1431
+ }
1432
+ }
1433
+ async function runCommand(command, shell, opts) {
1434
+ // Build opts without injecting undefined (exactOptionalPropertyTypes-safe)
1435
+ const callOpts = {};
1436
+ if (opts.cwd !== undefined) {
1437
+ callOpts.cwd = opts.cwd;
1438
+ }
1439
+ if (opts.env !== undefined) {
1440
+ callOpts.env = opts.env;
1441
+ }
1442
+ if (opts.stdio !== undefined)
1443
+ callOpts.stdio = opts.stdio;
1444
+ const ok = await _execNormalized(command, shell, callOpts);
1445
+ if (opts.stdio === 'pipe' && ok.stdout) {
1446
+ process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
1447
+ }
1448
+ return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
1449
+ }
1450
+
1451
+ /**
1452
+ * Attach root flags to a {@link GetDotenvCli} instance.
1453
+ *
1454
+ * Program is typed as {@link GetDotenvCli} and supports {@link GetDotenvCli.createDynamicOption | createDynamicOption}.
1455
+ */
1456
+ const attachRootOptions = (program, defaults) => {
1457
+ const GROUP = 'base';
1458
+ const { defaultEnv, dotenvToken, dynamicPath, env, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1459
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1460
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1461
+ // Helper: append (default) tags for ON/OFF toggles
1462
+ const onOff = (on, isDefault) => on
1463
+ ? `ON${isDefault ? ' (default)' : ''}`
1464
+ : `OFF${isDefault ? ' (default)' : ''}`;
1465
+ program.enablePositionalOptions().passThroughOptions();
1466
+ // -e, --env <string>
1467
+ {
1468
+ const opt = new Option('-e, --env <string>', 'target environment (dotenv-expanded)');
1469
+ opt.argParser(dotenvExpandFromProcessEnv);
1470
+ if (env !== undefined)
1471
+ opt.default(env);
1472
+ program.addOption(opt);
1473
+ program.setOptionGroup(opt, GROUP);
1474
+ }
1475
+ // -v, --vars <string>
1476
+ {
1477
+ const examples = [
1478
+ ['KEY1', 'VAL1'],
1479
+ ['KEY2', 'VAL2'],
1480
+ ]
1481
+ .map((v) => v.join(va))
1482
+ .join(vd);
1483
+ const opt = new Option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${examples}`);
1484
+ opt.argParser(dotenvExpandFromProcessEnv);
1485
+ program.addOption(opt);
1486
+ program.setOptionGroup(opt, GROUP);
1487
+ }
1488
+ // Output path (interpolated later; help can remain static)
1489
+ {
1490
+ const opt = new Option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)');
1491
+ opt.argParser(dotenvExpandFromProcessEnv);
1492
+ if (outputPath !== undefined)
1493
+ opt.default(outputPath);
1494
+ program.addOption(opt);
1495
+ program.setOptionGroup(opt, GROUP);
1496
+ }
1497
+ // Shell ON (string or boolean true => default shell)
1498
+ {
1499
+ const opt = program
1500
+ .createDynamicOption('-s, --shell [string]', (cfg) => {
1501
+ const s = cfg.shell;
1502
+ let tag = '';
1503
+ if (typeof s === 'boolean' && s)
1504
+ tag = ' (default OS shell)';
1505
+ else if (typeof s === 'string' && s.length > 0)
1506
+ tag = ` (default ${s})`;
1507
+ return `command execution shell, no argument for default OS shell or provide shell string${tag}`;
1508
+ })
1509
+ .conflicts('shellOff');
1510
+ program.addOption(opt);
1511
+ program.setOptionGroup(opt, GROUP);
1512
+ }
1513
+ // Shell OFF
1514
+ {
1515
+ const opt = program
1516
+ .createDynamicOption('-S, --shell-off', (cfg) => {
1517
+ const s = cfg.shell;
1518
+ return `command execution shell OFF${s === false ? ' (default)' : ''}`;
1519
+ })
1520
+ .conflicts('shell');
1521
+ program.addOption(opt);
1522
+ program.setOptionGroup(opt, GROUP);
1523
+ }
1524
+ // Load process ON/OFF (dynamic defaults)
1525
+ {
1526
+ const optOn = program
1527
+ .createDynamicOption('-p, --load-process', (cfg) => `load variables to process.env ${onOff(true, Boolean(cfg.loadProcess))}`)
1528
+ .conflicts('loadProcessOff');
1529
+ program.addOption(optOn);
1530
+ program.setOptionGroup(optOn, GROUP);
1531
+ const optOff = program
1532
+ .createDynamicOption('-P, --load-process-off', (cfg) => `load variables to process.env ${onOff(false, !cfg.loadProcess)}`)
1533
+ .conflicts('loadProcess');
1534
+ program.addOption(optOff);
1535
+ program.setOptionGroup(optOff, GROUP);
1536
+ }
1537
+ // Exclusion master toggle (dynamic)
1538
+ {
1539
+ const optAll = program
1540
+ .createDynamicOption('-a, --exclude-all', (cfg) => {
1541
+ const allOn = !!cfg.excludeDynamic &&
1542
+ ((!!cfg.excludeEnv && !!cfg.excludeGlobal) ||
1543
+ (!!cfg.excludePrivate && !!cfg.excludePublic));
1544
+ const suffix = allOn ? ' (default)' : '';
1545
+ return `exclude all dotenv variables from loading ON${suffix}`;
1546
+ })
1547
+ .conflicts('excludeAllOff');
1548
+ program.addOption(optAll);
1549
+ program.setOptionGroup(optAll, GROUP);
1550
+ const optAllOff = new Option('-A, --exclude-all-off', 'exclude all dotenv variables from loading OFF (default)').conflicts('excludeAll');
1551
+ program.addOption(optAllOff);
1552
+ program.setOptionGroup(optAllOff, GROUP);
1553
+ }
1554
+ // Per-family exclusions (dynamic defaults)
1555
+ {
1556
+ const o1 = program
1557
+ .createDynamicOption('-z, --exclude-dynamic', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(true, Boolean(cfg.excludeDynamic))}`)
1558
+ .conflicts('excludeDynamicOff');
1559
+ program.addOption(o1);
1560
+ program.setOptionGroup(o1, GROUP);
1561
+ const o2 = program
1562
+ .createDynamicOption('-Z, --exclude-dynamic-off', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(false, !cfg.excludeDynamic)}`)
1563
+ .conflicts('excludeDynamic');
1564
+ program.addOption(o2);
1565
+ program.setOptionGroup(o2, GROUP);
1566
+ }
1567
+ {
1568
+ const o1 = program
1569
+ .createDynamicOption('-n, --exclude-env', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(true, Boolean(cfg.excludeEnv))}`)
1570
+ .conflicts('excludeEnvOff');
1571
+ program.addOption(o1);
1572
+ program.setOptionGroup(o1, GROUP);
1573
+ const o2 = program
1574
+ .createDynamicOption('-N, --exclude-env-off', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(false, !cfg.excludeEnv)}`)
1575
+ .conflicts('excludeEnv');
1576
+ program.addOption(o2);
1577
+ program.setOptionGroup(o2, GROUP);
1578
+ }
1579
+ {
1580
+ const o1 = program
1581
+ .createDynamicOption('-g, --exclude-global', (cfg) => `exclude global dotenv variables from loading ${onOff(true, Boolean(cfg.excludeGlobal))}`)
1582
+ .conflicts('excludeGlobalOff');
1583
+ program.addOption(o1);
1584
+ program.setOptionGroup(o1, GROUP);
1585
+ const o2 = program
1586
+ .createDynamicOption('-G, --exclude-global-off', (cfg) => `exclude global dotenv variables from loading ${onOff(false, !cfg.excludeGlobal)}`)
1587
+ .conflicts('excludeGlobal');
1588
+ program.addOption(o2);
1589
+ program.setOptionGroup(o2, GROUP);
1590
+ }
1591
+ {
1592
+ const p1 = program
1593
+ .createDynamicOption('-r, --exclude-private', (cfg) => `exclude private dotenv variables from loading ${onOff(true, Boolean(cfg.excludePrivate))}`)
1594
+ .conflicts('excludePrivateOff');
1595
+ program.addOption(p1);
1596
+ program.setOptionGroup(p1, GROUP);
1597
+ const p2 = program
1598
+ .createDynamicOption('-R, --exclude-private-off', (cfg) => `exclude private dotenv variables from loading ${onOff(false, !cfg.excludePrivate)}`)
1599
+ .conflicts('excludePrivate');
1600
+ program.addOption(p2);
1601
+ program.setOptionGroup(p2, GROUP);
1602
+ const pu1 = program
1603
+ .createDynamicOption('-u, --exclude-public', (cfg) => `exclude public dotenv variables from loading ${onOff(true, Boolean(cfg.excludePublic))}`)
1604
+ .conflicts('excludePublicOff');
1605
+ program.addOption(pu1);
1606
+ program.setOptionGroup(pu1, GROUP);
1607
+ const pu2 = program
1608
+ .createDynamicOption('-U, --exclude-public-off', (cfg) => `exclude public dotenv variables from loading ${onOff(false, !cfg.excludePublic)}`)
1609
+ .conflicts('excludePublic');
1610
+ program.addOption(pu2);
1611
+ program.setOptionGroup(pu2, GROUP);
1612
+ }
1613
+ // Log ON/OFF (dynamic)
1614
+ {
1615
+ const lo = program
1616
+ .createDynamicOption('-l, --log', (cfg) => `console log loaded variables ${onOff(true, Boolean(cfg.log))}`)
1617
+ .conflicts('logOff');
1618
+ program.addOption(lo);
1619
+ program.setOptionGroup(lo, GROUP);
1620
+ const lf = program
1621
+ .createDynamicOption('-L, --log-off', (cfg) => `console log loaded variables ${onOff(false, !cfg.log)}`)
1622
+ .conflicts('log');
1623
+ program.addOption(lf);
1624
+ program.setOptionGroup(lf, GROUP);
1625
+ }
1626
+ // Capture flag (no default display; static)
1627
+ {
1628
+ const opt = new Option('--capture', 'capture child process stdio for commands (tests/CI)');
1629
+ program.addOption(opt);
1630
+ program.setOptionGroup(opt, GROUP);
1631
+ }
1632
+ // Core bootstrap/static flags (kept static in help)
1633
+ {
1634
+ const o1 = new Option('--default-env <string>', 'default target environment');
1635
+ o1.argParser(dotenvExpandFromProcessEnv);
1636
+ if (defaultEnv !== undefined)
1637
+ o1.default(defaultEnv);
1638
+ program.addOption(o1);
1639
+ program.setOptionGroup(o1, GROUP);
1640
+ const o2 = new Option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file');
1641
+ o2.argParser(dotenvExpandFromProcessEnv);
1642
+ if (dotenvToken !== undefined)
1643
+ o2.default(dotenvToken);
1644
+ program.addOption(o2);
1645
+ program.setOptionGroup(o2, GROUP);
1646
+ const o3 = new Option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)');
1647
+ o3.argParser(dotenvExpandFromProcessEnv);
1648
+ if (dynamicPath !== undefined)
1649
+ o3.default(dynamicPath);
1650
+ program.addOption(o3);
1651
+ program.setOptionGroup(o3, GROUP);
1652
+ const o4 = new Option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory');
1653
+ o4.argParser(dotenvExpandFromProcessEnv);
1654
+ if (paths !== undefined)
1655
+ o4.default(paths);
1656
+ program.addOption(o4);
1657
+ program.setOptionGroup(o4, GROUP);
1658
+ const o5 = new Option('--paths-delimiter <string>', 'paths delimiter string');
1659
+ if (pathsDelimiter !== undefined)
1660
+ o5.default(pathsDelimiter);
1661
+ program.addOption(o5);
1662
+ program.setOptionGroup(o5, GROUP);
1663
+ const o6 = new Option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern');
1664
+ if (pathsDelimiterPattern !== undefined)
1665
+ o6.default(pathsDelimiterPattern);
1666
+ program.addOption(o6);
1667
+ program.setOptionGroup(o6, GROUP);
1668
+ const o7 = new Option('--private-token <string>', 'dotenv-expanded token indicating private variables');
1669
+ o7.argParser(dotenvExpandFromProcessEnv);
1670
+ if (privateToken !== undefined)
1671
+ o7.default(privateToken);
1672
+ program.addOption(o7);
1673
+ program.setOptionGroup(o7, GROUP);
1674
+ const o8 = new Option('--vars-delimiter <string>', 'vars delimiter string');
1675
+ if (varsDelimiter !== undefined)
1676
+ o8.default(varsDelimiter);
1677
+ program.addOption(o8);
1678
+ program.setOptionGroup(o8, GROUP);
1679
+ const o9 = new Option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern');
1680
+ if (varsDelimiterPattern !== undefined)
1681
+ o9.default(varsDelimiterPattern);
1682
+ program.addOption(o9);
1683
+ program.setOptionGroup(o9, GROUP);
1684
+ const o10 = new Option('--vars-assignor <string>', 'vars assignment operator string');
1685
+ if (varsAssignor !== undefined)
1686
+ o10.default(varsAssignor);
1687
+ program.addOption(o10);
1688
+ program.setOptionGroup(o10, GROUP);
1689
+ const o11 = new Option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern');
1690
+ if (varsAssignorPattern !== undefined)
1691
+ o11.default(varsAssignorPattern);
1692
+ program.addOption(o11);
1693
+ program.setOptionGroup(o11, GROUP);
1694
+ }
1695
+ // Diagnostics / validation / entropy
1696
+ {
1697
+ const tr = new Option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1698
+ program.addOption(tr);
1699
+ program.setOptionGroup(tr, GROUP);
1700
+ const st = new Option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1701
+ program.addOption(st);
1702
+ program.setOptionGroup(st, GROUP);
1703
+ }
1704
+ {
1705
+ const w = program
1706
+ .createDynamicOption('--entropy-warn', (cfg) => {
1707
+ const warn = cfg.warnEntropy;
1708
+ // Default is effectively ON when warnEntropy is true or undefined.
1709
+ return `enable entropy warnings${warn === false ? '' : ' (default on)'}`;
1710
+ })
1711
+ .conflicts('entropyWarnOff');
1712
+ program.addOption(w);
1713
+ program.setOptionGroup(w, GROUP);
1714
+ const woff = program
1715
+ .createDynamicOption('--entropy-warn-off', (cfg) => `disable entropy warnings${cfg.warnEntropy === false ? ' (default)' : ''}`)
1716
+ .conflicts('entropyWarn');
1717
+ program.addOption(woff);
1718
+ program.setOptionGroup(woff, GROUP);
1719
+ const th = new Option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)');
1720
+ program.addOption(th);
1721
+ program.setOptionGroup(th, GROUP);
1722
+ const ml = new Option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)');
1723
+ program.addOption(ml);
1724
+ program.setOptionGroup(ml, GROUP);
1725
+ const wl = new Option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern');
1726
+ program.addOption(wl);
1727
+ program.setOptionGroup(wl, GROUP);
1728
+ const rp = new Option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1729
+ program.addOption(rp);
1730
+ program.setOptionGroup(rp, GROUP);
1731
+ // Redact ON/OFF (dynamic)
1732
+ {
1733
+ const rOn = program
1734
+ .createDynamicOption('--redact', (cfg) => `presentation-time redaction for secret-like keys ON${cfg.redact ? ' (default)' : ''}`)
1735
+ .conflicts('redactOff');
1736
+ program.addOption(rOn);
1737
+ program.setOptionGroup(rOn, GROUP);
1738
+ const rOff = program
1739
+ .createDynamicOption('--redact-off', (cfg) => `presentation-time redaction for secret-like keys OFF${cfg.redact === false ? ' (default)' : ''}`)
1740
+ .conflicts('redact');
1741
+ program.addOption(rOff);
1742
+ program.setOptionGroup(rOff, GROUP);
1743
+ }
1744
+ }
1745
+ return program;
1746
+ };
1747
+
1748
+ /**
1749
+ * Registry for option grouping.
1750
+ * Root help renders these groups between "Options" and "Commands".
1751
+ */
1752
+ const GROUP_TAG = new WeakMap();
1753
+ /**
1754
+ * Render help option groups (App/Plugins) for a given command.
1755
+ * Groups are injected between Options and Commands in the help output.
1756
+ */
1757
+ function renderOptionGroups(cmd) {
1758
+ const all = cmd.options;
1759
+ const byGroup = new Map();
1760
+ for (const o of all) {
1761
+ const opt = o;
1762
+ const g = GROUP_TAG.get(opt);
1763
+ if (!g || g === 'base')
1764
+ continue; // base handled by default help
1765
+ const rows = byGroup.get(g) ?? [];
1766
+ rows.push({
1767
+ flags: opt.flags,
1768
+ description: opt.description ?? '',
1769
+ });
1770
+ byGroup.set(g, rows);
1771
+ }
1772
+ if (byGroup.size === 0)
1773
+ return '';
1774
+ const renderRows = (title, rows) => {
1775
+ const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1776
+ // Sort within group: short-aliased flags first
1777
+ rows.sort((a, b) => {
1778
+ const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1779
+ const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1780
+ return bS - aS || a.flags.localeCompare(b.flags);
1781
+ });
1782
+ const lines = rows
1783
+ .map((r) => {
1784
+ const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1785
+ return ` ${r.flags}${pad}${r.description}`.trimEnd();
1786
+ })
1787
+ .join('\n');
1788
+ return `\n${title}:\n${lines}\n`;
1789
+ };
1790
+ let out = '';
1791
+ // App options (if any)
1792
+ const app = byGroup.get('app');
1793
+ if (app && app.length > 0) {
1794
+ out += renderRows('App options', app);
1795
+ }
1796
+ // Plugin groups sorted by id; suppress self group on the owning command name.
1797
+ const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1798
+ const currentName = cmd.name();
1799
+ pluginKeys.sort((a, b) => a.localeCompare(b));
1800
+ for (const k of pluginKeys) {
1801
+ const id = k.slice('plugin:'.length) || '(unknown)';
1802
+ const rows = byGroup.get(k) ?? [];
1803
+ if (rows.length > 0 && id !== currentName) {
1804
+ out += renderRows(`Plugin options — ${id}`, rows);
1805
+ }
1806
+ }
1807
+ return out;
1808
+ }
1809
+
1810
+ /**
1811
+ * Compose root/parent help output by inserting grouped sections between
1812
+ * Options and Commands, ensuring a trailing blank line.
1813
+ *
1814
+ * @param base - Base help text produced by Commander.
1815
+ * @param cmd - Command instance whose grouped options should be rendered.
1816
+ * @returns The modified help text with grouped blocks inserted.
1817
+ */
1818
+ function buildHelpInformation(base, cmd) {
1819
+ const groups = renderOptionGroups(cmd);
1820
+ const block = typeof groups === 'string' ? groups.trim() : '';
1821
+ if (!block) {
1822
+ return base.endsWith('\n\n')
1823
+ ? base
1824
+ : base.endsWith('\n')
1825
+ ? `${base}\n`
1826
+ : `${base}\n\n`;
1827
+ }
1828
+ const marker = '\nCommands:';
1829
+ const idx = base.indexOf(marker);
1830
+ let out = base;
1831
+ if (idx >= 0) {
1832
+ const toInsert = groups.startsWith('\n') ? groups : `\n${groups}`;
1833
+ out = `${base.slice(0, idx)}${toInsert}${base.slice(idx)}`;
1834
+ }
1835
+ else {
1836
+ const sep = base.endsWith('\n') || groups.startsWith('\n') ? '' : '\n';
1837
+ out = `${base}${sep}${groups}`;
1838
+ }
1839
+ return out.endsWith('\n\n')
1840
+ ? out
1841
+ : out.endsWith('\n')
1842
+ ? `${out}\n`
1843
+ : `${out}\n\n`;
1844
+ }
1845
+
1846
+ /** src/cliHost/GetDotenvCli/dynamicOptions.ts
1847
+ * Helpers for dynamic option descriptions and evaluation.
1848
+ */
1849
+ /**
1850
+ * Registry for dynamic descriptions keyed by Option (WeakMap for GC safety).
1851
+ */
1852
+ const DYN_DESC = new WeakMap();
1853
+ /**
1854
+ * Create an Option with a dynamic description callback stored in DYN_DESC.
1855
+ */
1856
+ function makeDynamicOption(flags, desc, parser, defaultValue) {
1857
+ const opt = new Option(flags, '');
1858
+ DYN_DESC.set(opt, desc);
1859
+ if (parser) {
1860
+ opt.argParser((value, previous) => parser(value, previous));
1861
+ }
1862
+ if (defaultValue !== undefined)
1863
+ opt.default(defaultValue);
1864
+ // Commander.Option is structurally compatible; help-time wiring is stored in DYN_DESC.
1865
+ return opt;
1866
+ }
1867
+ /**
1868
+ * Evaluate dynamic descriptions across a command tree using the resolved config.
1869
+ */
1870
+ function evaluateDynamicOptions(root, resolved) {
1871
+ const visit = (cmd) => {
1872
+ const arr = cmd.options;
1873
+ for (const o of arr) {
1874
+ const dyn = DYN_DESC.get(o);
1875
+ if (typeof dyn === 'function') {
1876
+ try {
1877
+ const txt = dyn(resolved);
1878
+ // Commander uses Option.description during help rendering.
1879
+ o.description = txt;
1880
+ }
1881
+ catch {
1882
+ /* best-effort; leave as-is */
1883
+ }
1884
+ }
1885
+ }
1886
+ for (const c of cmd.commands)
1887
+ visit(c);
1888
+ };
1889
+ visit(root);
1890
+ }
1891
+
1892
+ function initializeInstance(cli, headerGetter) {
1893
+ // Configure grouped help: show only base options in default "Options";
1894
+ // subcommands show all of their own options.
1895
+ cli.configureHelp({
1896
+ visibleOptions: (cmd) => {
1897
+ const all = cmd.options;
1898
+ const isRoot = cmd.parent === null;
1899
+ const list = isRoot
1900
+ ? all.filter((opt) => {
1901
+ const group = GROUP_TAG.get(opt);
1902
+ return group === 'base';
1903
+ })
1904
+ : all.slice();
1905
+ // Sort: short-aliased options first, then long-only; stable by flags.
1906
+ const hasShort = (opt) => {
1907
+ const flags = opt.flags;
1908
+ return /(^|\s|,)-[A-Za-z]/.test(flags);
1909
+ };
1910
+ const byFlags = (opt) => opt.flags;
1911
+ list.sort((a, b) => {
1912
+ const aS = hasShort(a) ? 1 : 0;
1913
+ const bS = hasShort(b) ? 1 : 0;
1914
+ return bS - aS || byFlags(a).localeCompare(byFlags(b));
1915
+ });
1916
+ return list;
1917
+ },
1918
+ });
1919
+ // Optional branded header before help text (kept minimal and deterministic).
1920
+ cli.addHelpText('beforeAll', () => {
1921
+ const header = headerGetter();
1922
+ return header && header.length > 0 ? `${header}\n\n` : '';
1923
+ });
1924
+ // Tests-only: suppress process.exit during help/version flows under Vitest.
1925
+ // Unit tests often construct GetDotenvCli directly (bypassing createCli),
1926
+ // so install a local exitOverride when a test environment is detected.
1927
+ const underTests = process.env.GETDOTENV_TEST === '1' ||
1928
+ typeof process.env.VITEST_WORKER_ID === 'string';
1929
+ if (underTests) {
1930
+ cli.exitOverride((err) => {
1931
+ const code = err?.code;
1932
+ if (code === 'commander.helpDisplayed' ||
1933
+ code === 'commander.version' ||
1934
+ code === 'commander.help')
1935
+ return;
1936
+ throw err;
1937
+ });
1938
+ }
1939
+ // Ensure the root has a no-op action so preAction hooks installed by
1940
+ // passOptions() fire for root-only invocations (no subcommand).
1941
+ // Subcommands still take precedence and will not hit this action.
1942
+ // This keeps root-side effects (e.g., --log) working in direct hosts/tests.
1943
+ cli.action(() => {
1944
+ /* no-op */
1945
+ });
1946
+ // PreSubcommand hook: compute a context if absent, without mutating process.env.
1947
+ // The passOptions() helper, when installed, resolves the final context.
1948
+ cli.hook('preSubcommand', async () => {
1949
+ if (cli.hasCtx())
1950
+ return;
1951
+ await cli.resolveAndLoad({ loadProcess: false });
1952
+ });
1953
+ }
1954
+
1955
+ /**
1956
+ * Determine the effective namespace for a child plugin (override \> default).
1957
+ */
1958
+ const effectiveNs = (child) => {
1959
+ const o = child.override;
1960
+ return (o && typeof o.ns === 'string' && o.ns.length > 0 ? o.ns : child.plugin.ns).trim();
1961
+ };
1962
+ const isPromise = (v) => !!v && typeof v.then === 'function';
1963
+ function runInstall(parentCli, plugin) {
1964
+ // Create mount and run setup
1965
+ const mount = parentCli.ns(plugin.ns);
1966
+ const setupRet = plugin.setup(mount);
1967
+ const pending = [];
1968
+ if (isPromise(setupRet))
1969
+ pending.push(setupRet.then(() => undefined));
1970
+ // Enforce sibling uniqueness before creating children
1971
+ const names = new Set();
1972
+ for (const entry of plugin.children) {
1973
+ const ns = effectiveNs(entry);
1974
+ if (names.has(ns)) {
1975
+ const under = mount.name();
1976
+ throw new Error(`Duplicate namespace '${ns}' under '${under || 'root'}'. Override via .use(plugin, { ns: '...' }).`);
1977
+ }
1978
+ names.add(ns);
1979
+ }
1980
+ // Install children (pre-order), synchronously when possible
1981
+ for (const entry of plugin.children) {
1982
+ const childRet = runInstall(mount, entry.plugin);
1983
+ if (isPromise(childRet))
1984
+ pending.push(childRet);
1985
+ }
1986
+ if (pending.length > 0)
1987
+ return Promise.all(pending).then(() => undefined);
1988
+ return;
1989
+ }
1990
+ /**
1991
+ * Install a plugin and its children (pre-order setup phase).
1992
+ * Enforces sibling namespace uniqueness.
1993
+ */
1994
+ function setupPluginTree(cli, plugin) {
1995
+ const ret = runInstall(cli, plugin);
1996
+ return isPromise(ret) ? ret : Promise.resolve();
1997
+ }
1998
+
1999
+ /**
2000
+ * Resolve options strictly and compute the dotenv context via the loader/overlay path.
2001
+ *
2002
+ * @param customOptions - Partial options overlay.
2003
+ * @param plugins - Plugins list for config validation.
2004
+ * @param hostMetaUrl - Import URL for resolving the packaged root.
2005
+ */
2006
+ async function resolveAndComputeContext(customOptions, plugins, hostMetaUrl) {
2007
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
2008
+ // Strict schema validation
2009
+ getDotenvOptionsSchemaResolved.parse(optionsResolved);
2010
+ const ctx = await computeContext(optionsResolved, plugins, hostMetaUrl);
2011
+ return ctx;
2012
+ }
2013
+
2014
+ /**
2015
+ * Run afterResolve hooks for a plugin tree (parent → children).
2016
+ */
2017
+ async function runAfterResolveTree(cli, plugins, ctx) {
2018
+ const run = async (p) => {
2019
+ if (p.afterResolve)
2020
+ await p.afterResolve(cli, ctx);
2021
+ for (const child of p.children)
2022
+ await run(child.plugin);
2023
+ };
2024
+ for (const p of plugins)
2025
+ await run(p);
2026
+ }
2027
+
2028
+ /**
2029
+ * Temporarily tag options added during a callback as 'app' for grouped help.
2030
+ * Wraps `addOption` on the command instance.
2031
+ */
2032
+ function tagAppOptionsAround(root, setOptionGroup, fn) {
2033
+ const originalAddOption = root.addOption.bind(root);
2034
+ root.addOption = ((opt) => {
2035
+ setOptionGroup(opt, 'app');
2036
+ return originalAddOption(opt);
2037
+ });
2038
+ try {
2039
+ return fn(root);
2040
+ }
2041
+ finally {
2042
+ root.addOption = originalAddOption;
2043
+ }
2044
+ }
2045
+
2046
+ /**
2047
+ * Read the version from the nearest `package.json` relative to the provided import URL.
2048
+ *
2049
+ * @param importMetaUrl - The `import.meta.url` of the calling module.
2050
+ * @returns The version string or undefined if not found.
2051
+ */
2052
+ async function readPkgVersion(importMetaUrl) {
2053
+ if (!importMetaUrl)
2054
+ return undefined;
2055
+ try {
2056
+ const fromUrl = fileURLToPath(importMetaUrl);
2057
+ const pkgDir = await packageDirectory({ cwd: fromUrl });
2058
+ if (!pkgDir)
2059
+ return undefined;
2060
+ const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
2061
+ const pkg = JSON.parse(txt);
2062
+ return pkg.version ?? undefined;
2063
+ }
2064
+ catch {
2065
+ // best-effort only
2066
+ return undefined;
2067
+ }
2068
+ }
2069
+
2070
+ /** src/cliHost/GetDotenvCli.ts
2071
+ * Plugin-first CLI host for get-dotenv with Commander generics preserved.
2072
+ * Public surface implements GetDotenvCliPublic and provides:
2073
+ * - attachRootOptions (builder-only; no public override wiring)
2074
+ * - resolveAndLoad (strict resolve + context compute)
2075
+ * - getCtx/hasCtx accessors
2076
+ * - ns() for typed subcommand creation with duplicate-name guard
2077
+ * - grouped help rendering with dynamic option descriptions
2078
+ */
2079
+ const HOST_META_URL = import.meta.url;
2080
+ const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
2081
+ const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
2082
+ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
2083
+ /**
2084
+ * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
2085
+ *
2086
+ * Responsibilities:
2087
+ * - Resolve options strictly and compute dotenv context (resolveAndLoad).
2088
+ * - Expose a stable accessor for the current context (getCtx).
2089
+ * - Provide a namespacing helper (ns).
2090
+ * - Support composable plugins with parent → children install and afterResolve.
2091
+ */
2092
+ class GetDotenvCli extends Command {
2093
+ /** Registered top-level plugins (composition happens via .use()) */
2094
+ _plugins = [];
2095
+ /** One-time installation guard */
2096
+ _installed = false;
2097
+ /** In-flight installation promise to guard against concurrent installs */
2098
+ _installing;
2099
+ /** Optional header line to prepend in help output */
2100
+ [HELP_HEADER_SYMBOL];
2101
+ /** Context/options stored under symbols (typed) */
2102
+ [CTX_SYMBOL];
2103
+ [OPTS_SYMBOL];
2104
+ /**
2105
+ * Create a subcommand using the same subclass, preserving helpers like
2106
+ * dynamicOption on children.
2107
+ */
2108
+ createCommand(name) {
2109
+ // Explicitly construct a GetDotenvCli for children to preserve helpers.
2110
+ return new GetDotenvCli(name);
2111
+ }
2112
+ constructor(alias = 'getdotenv') {
2113
+ super(alias);
2114
+ this.enablePositionalOptions();
2115
+ // Delegate the heavy setup to a helper to keep the constructor lean.
2116
+ initializeInstance(this, () => this[HELP_HEADER_SYMBOL]);
2117
+ }
2118
+ /**
2119
+ * Attach legacy/base root flags to this CLI instance.
2120
+ * Delegates to the pure builder in attachRootOptions.ts.
2121
+ */
2122
+ attachRootOptions(defaults) {
2123
+ const d = (defaults ?? baseRootOptionDefaults);
2124
+ attachRootOptions(this, d);
2125
+ return this;
2126
+ }
2127
+ /**
2128
+ * Resolve options (strict) and compute dotenv context.
2129
+ * Stores the context on the instance under a symbol.
2130
+ *
2131
+ * Options:
2132
+ * - opts.runAfterResolve (default true): when false, skips running plugin
2133
+ * afterResolve hooks. Useful for top-level help rendering to avoid
2134
+ * long-running side-effects while still evaluating dynamic help text.
2135
+ */
2136
+ async resolveAndLoad(customOptions = {}, opts) {
2137
+ const ctx = await resolveAndComputeContext(customOptions,
2138
+ // Pass only plugin instances to the resolver (not entries with overrides)
2139
+ this._plugins.map((e) => e.plugin), HOST_META_URL);
2140
+ // Persist context on the instance for later access.
2141
+ this[CTX_SYMBOL] = ctx;
2142
+ // Ensure plugins are installed exactly once, then run afterResolve.
2143
+ await this.install();
2144
+ if (opts?.runAfterResolve ?? true) {
2145
+ await this._runAfterResolve(ctx);
2146
+ }
2147
+ return ctx;
2148
+ }
2149
+ // Implementation
2150
+ createDynamicOption(flags, desc, parser, defaultValue) {
2151
+ return makeDynamicOption(flags, (c) => desc(c), parser, defaultValue);
2152
+ }
2153
+ /**
2154
+ * Evaluate dynamic descriptions for this command and all descendants using
2155
+ * the provided resolved configuration. Mutates the Option.description in
2156
+ * place so Commander help renders updated text.
2157
+ */
2158
+ evaluateDynamicOptions(resolved) {
2159
+ evaluateDynamicOptions(this, resolved);
2160
+ }
2161
+ /** Internal: climb to the true root (host) command. */
2162
+ _root() {
2163
+ let node = this;
2164
+ while (node.parent) {
2165
+ node = node.parent;
2166
+ }
2167
+ return node;
2168
+ }
2169
+ /**
2170
+ * Retrieve the current invocation context (if any).
2171
+ */
2172
+ getCtx() {
2173
+ let ctx = this[CTX_SYMBOL];
2174
+ if (!ctx) {
2175
+ const root = this._root();
2176
+ ctx = root[CTX_SYMBOL];
2177
+ }
2178
+ if (!ctx) {
2179
+ throw new Error('Dotenv context unavailable. Ensure resolveAndLoad() has been called or the host is wired with passOptions() before invoking commands.');
2180
+ }
2181
+ return ctx;
2182
+ }
2183
+ /**
2184
+ * Check whether a context has been resolved (non-throwing guard).
2185
+ */
2186
+ hasCtx() {
2187
+ if (this[CTX_SYMBOL] !== undefined)
2188
+ return true;
2189
+ const root = this._root();
2190
+ return root[CTX_SYMBOL] !== undefined;
2191
+ }
2192
+ /**
2193
+ * Retrieve the merged root CLI options bag (if set by passOptions()).
2194
+ * Downstream-safe: no generics required.
2195
+ */
2196
+ getOptions() {
2197
+ if (this[OPTS_SYMBOL])
2198
+ return this[OPTS_SYMBOL];
2199
+ const root = this._root();
2200
+ const bag = root[OPTS_SYMBOL];
2201
+ if (bag)
2202
+ return bag;
2203
+ return undefined;
2204
+ }
2205
+ /** Internal: set the merged root options bag for this run. */
2206
+ _setOptionsBag(bag) {
2207
+ this[OPTS_SYMBOL] = bag;
2208
+ }
2209
+ /**
2210
+ * Convenience helper to create a namespaced subcommand with argument inference.
2211
+ * This mirrors Commander generics so downstream chaining stays fully typed.
2212
+ */
2213
+ ns(name) {
2214
+ // Guard against same-level duplicate command names for clearer diagnostics.
2215
+ const exists = this.commands.some((c) => c.name() === name);
2216
+ if (exists) {
2217
+ throw new Error(`Duplicate command name: ${name}`);
2218
+ }
2219
+ return this.command(name);
2220
+ }
2221
+ /**
2222
+ * Tag options added during the provided callback as 'app' for grouped help.
2223
+ * Allows downstream apps to demarcate their root-level options.
2224
+ */
2225
+ tagAppOptions(fn) {
2226
+ return tagAppOptionsAround(this, this.setOptionGroup.bind(this), fn);
2227
+ }
2228
+ /**
2229
+ * Branding helper: set CLI name/description/version and optional help header.
2230
+ * If version is omitted and importMetaUrl is provided, attempts to read the
2231
+ * nearest package.json version (best-effort; non-fatal on failure).
2232
+ */
2233
+ async brand(args) {
2234
+ const { name, description, version, importMetaUrl, helpHeader } = args;
2235
+ if (typeof name === 'string' && name.length > 0)
2236
+ this.name(name);
2237
+ if (typeof description === 'string')
2238
+ this.description(description);
2239
+ const v = version ?? (await readPkgVersion(importMetaUrl));
2240
+ if (v)
2241
+ this.version(v);
2242
+ // Help header:
2243
+ // - If caller provides helpHeader, use it.
2244
+ // - Otherwise, when a version is known, default to "<name> v<version>".
2245
+ if (typeof helpHeader === 'string') {
2246
+ this[HELP_HEADER_SYMBOL] = helpHeader;
2247
+ }
2248
+ else if (v) {
2249
+ const header = `${this.name()} v${v}`;
2250
+ this[HELP_HEADER_SYMBOL] = header;
2251
+ }
2252
+ return this;
2253
+ }
2254
+ /**
2255
+ * Insert grouped plugin/app options between "Options" and "Commands" for
2256
+ * hybrid ordering. Applies to root and any parent command.
2257
+ */
2258
+ helpInformation() {
2259
+ return buildHelpInformation(super.helpInformation(), this);
2260
+ }
2261
+ /**
2262
+ * Public: tag an Option with a display group for help (root/app/plugin:<id>).
2263
+ */
2264
+ setOptionGroup(opt, group) {
2265
+ GROUP_TAG.set(opt, group);
2266
+ }
2267
+ /**
2268
+ * Register a plugin for installation (parent level).
2269
+ * Installation occurs on first resolveAndLoad() (or explicit install()).
2270
+ */
2271
+ use(plugin, override) {
2272
+ this._plugins.push({ plugin, override });
2273
+ return this;
2274
+ }
2275
+ /**
2276
+ * Install all registered plugins in parent → children (pre-order).
2277
+ * Runs only once per CLI instance.
2278
+ */
2279
+ async install() {
2280
+ if (this._installed)
2281
+ return;
2282
+ if (this._installing) {
2283
+ await this._installing;
2284
+ return;
2285
+ }
2286
+ this._installing = (async () => {
2287
+ // Install parent → children with host-created mounts (async-aware).
2288
+ for (const entry of this._plugins) {
2289
+ const p = entry.plugin;
2290
+ await setupPluginTree(this, p);
197
2291
  }
2292
+ this._installed = true;
2293
+ })();
2294
+ try {
2295
+ await this._installing;
2296
+ }
2297
+ finally {
2298
+ // leave _installing as resolved; subsequent calls return early via _installed
198
2299
  }
199
2300
  }
200
- if (cur)
201
- out.push(cur);
202
- return out;
203
- };
2301
+ /**
2302
+ * Run afterResolve hooks for all plugins (parent → children).
2303
+ */
2304
+ async _runAfterResolve(ctx) {
2305
+ await runAfterResolveTree(this, this._plugins.map((e) => e.plugin), ctx);
2306
+ }
2307
+ }
204
2308
 
205
- const dbg = (...args) => {
206
- if (process.env.GETDOTENV_DEBUG) {
207
- // Use stderr to avoid interfering with stdout assertions
208
- console.error('[getdotenv:run]', ...args);
2309
+ /**
2310
+ * Compose a child-process env overlay from dotenv and the merged CLI options bag.
2311
+ * Returns a shallow object including getDotenvCliOptions when serializable.
2312
+ *
2313
+ * @param merged - Resolved CLI options bag (or a JSON-serializable subset).
2314
+ * @param dotenv - Composed dotenv variables for the current invocation.
2315
+ * @returns A string-only env overlay suitable for child process spawning.
2316
+ */
2317
+ function composeNestedEnv(merged, dotenv) {
2318
+ const out = {};
2319
+ for (const [k, v] of Object.entries(dotenv)) {
2320
+ if (typeof v === 'string')
2321
+ out[k] = v;
209
2322
  }
210
- };
211
- // Strip repeated symmetric outer quotes (single or double) until stable.
212
- // This is safe for argv arrays passed to execa (no quoting needed) and avoids
213
- // passing quote characters through to Node (e.g., for `node -e "<code>"`).
214
- // Handles stacked quotes from shells like PowerShell: """code""" -> code.
215
- const stripOuterQuotes = (s) => {
216
- let out = s;
217
- // Repeatedly trim only when the entire string is wrapped in matching quotes.
218
- // Stop as soon as the ends are asymmetric or no quotes remain.
219
- while (out.length >= 2) {
220
- const a = out.charAt(0);
221
- const b = out.charAt(out.length - 1);
222
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
223
- if (!symmetric)
224
- break;
225
- out = out.slice(1, -1);
2323
+ try {
2324
+ const { logger: _omit, ...bag } = merged;
2325
+ const txt = JSON.stringify(bag);
2326
+ if (typeof txt === 'string')
2327
+ out.getDotenvCliOptions = txt;
2328
+ }
2329
+ catch {
2330
+ /* best-effort only */
226
2331
  }
227
2332
  return out;
2333
+ }
2334
+ /**
2335
+ * Strip one layer of symmetric outer quotes (single or double) from a string.
2336
+ *
2337
+ * @param s - Input string.
2338
+ * @returns `s` without one symmetric outer quote pair (when present).
2339
+ */
2340
+ const stripOne = (s) => {
2341
+ if (s.length < 2)
2342
+ return s;
2343
+ const a = s.charAt(0);
2344
+ const b = s.charAt(s.length - 1);
2345
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
2346
+ return symmetric ? s.slice(1, -1) : s;
228
2347
  };
229
- // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
230
- const pickResult = (r) => {
231
- const exit = r.exitCode;
232
- const stdoutVal = r.stdout;
233
- const stderrVal = r.stderr;
234
- return {
235
- exitCode: typeof exit === 'number' ? exit : Number.NaN,
236
- stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
237
- stderr: typeof stderrVal === 'string' ? stderrVal : '',
238
- };
239
- };
240
- // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
241
- // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
242
- const sanitizeEnv = (env) => {
243
- if (!env)
244
- return undefined;
245
- const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
246
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
247
- };
248
- async function runCommand(command, shell, opts) {
249
- if (shell === false) {
250
- let file;
251
- let args = [];
252
- if (typeof command === 'string') {
253
- const tokens = tokenize(command);
254
- file = tokens[0];
255
- args = tokens.slice(1);
256
- }
257
- else {
258
- file = command[0];
259
- args = command.slice(1).map(stripOuterQuotes);
260
- }
261
- if (!file)
262
- return 0;
263
- dbg('exec (plain)', { file, args, stdio: opts.stdio });
264
- // Build options without injecting undefined properties (exactOptionalPropertyTypes).
265
- const envSan = sanitizeEnv(opts.env);
266
- const plainOpts = {};
267
- if (opts.cwd !== undefined)
268
- plainOpts.cwd = opts.cwd;
269
- if (envSan !== undefined)
270
- plainOpts.env = envSan;
271
- if (opts.stdio !== undefined)
272
- plainOpts.stdio = opts.stdio;
273
- const ok = pickResult((await execa(file, args, plainOpts)));
274
- if (opts.stdio === 'pipe' && ok.stdout) {
275
- process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
276
- }
277
- dbg('exit (plain)', { exitCode: ok.exitCode });
278
- return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
279
- }
280
- else {
281
- const commandStr = typeof command === 'string' ? command : command.join(' ');
282
- dbg('exec (shell)', {
283
- shell: typeof shell === 'string' ? shell : 'custom',
284
- stdio: opts.stdio,
285
- command: commandStr,
286
- });
287
- const envSan = sanitizeEnv(opts.env);
288
- const shellOpts = { shell };
289
- if (opts.cwd !== undefined)
290
- shellOpts.cwd = opts.cwd;
291
- if (envSan !== undefined)
292
- shellOpts.env = envSan;
293
- if (opts.stdio !== undefined)
294
- shellOpts.stdio = opts.stdio;
295
- const ok = pickResult((await execaCommand(commandStr, shellOpts)));
296
- if (opts.stdio === 'pipe' && ok.stdout) {
297
- process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
2348
+ /**
2349
+ * Preserve argv array for Node -e/--eval payloads under shell-off and
2350
+ * peel one symmetric outer quote layer from the code argument.
2351
+ *
2352
+ * @param args - Argument vector intended for direct execution (shell-off).
2353
+ * @returns Either the original `args` or a modified copy with a normalized eval payload.
2354
+ */
2355
+ function maybePreserveNodeEvalArgv(args) {
2356
+ if (args.length >= 3) {
2357
+ const first = (args[0] ?? '').toLowerCase();
2358
+ const hasEval = args[1] === '-e' || args[1] === '--eval';
2359
+ if (first === 'node' && hasEval) {
2360
+ const copy = args.slice();
2361
+ copy[2] = stripOne(copy[2] ?? '');
2362
+ return copy;
298
2363
  }
299
- dbg('exit (shell)', { exitCode: ok.exitCode });
300
- return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
301
2364
  }
2365
+ return args;
302
2366
  }
303
2367
 
304
- /** src/cliCore/spawnEnv.ts
305
- * Build a sanitized environment bag for child processes.
2368
+ /**
2369
+ * Retrieve the merged root options bag from the current command context.
2370
+ * Climbs to the root `GetDotenvCli` instance to access the persisted options.
306
2371
  *
307
- * Requirements addressed:
308
- * - Provide a single helper (buildSpawnEnv) to normalize/dedupe child env.
309
- * - Drop undefined values (exactOptional semantics).
310
- * - On Windows, dedupe keys case-insensitively and prefer the last value,
311
- * preserving the latest key's casing. Ensure HOME fallback from USERPROFILE.
312
- * Normalize TMP/TEMP consistency when either is present.
313
- * - On POSIX, keep keys as-is; when a temp dir key is present (TMPDIR/TMP/TEMP),
314
- * ensure TMPDIR exists for downstream consumers that expect it.
2372
+ * @param cmd - The current command instance (thisCommand).
2373
+ * @throws Error if the root is not a GetDotenvCli or options are missing.
2374
+ */
2375
+ const readMergedOptions = (cmd) => {
2376
+ // Climb to the true root
2377
+ let root = cmd;
2378
+ while (root.parent)
2379
+ root = root.parent;
2380
+ // Assert we ended at our host
2381
+ if (!(root instanceof GetDotenvCli)) {
2382
+ throw new Error('readMergedOptions: root command is not a GetDotenvCli.' +
2383
+ 'Ensure your CLI is constructed with GetDotenvCli.');
2384
+ }
2385
+ // Require passOptions() to have persisted the bag
2386
+ const bag = root.getOptions();
2387
+ if (!bag || typeof bag !== 'object') {
2388
+ throw new Error('readMergedOptions: merged options are unavailable. ' +
2389
+ 'Call .passOptions() on the host before parsing.');
2390
+ }
2391
+ return bag;
2392
+ };
2393
+
2394
+ /**
2395
+ * Batch services (neutral): resolve command and shell settings.
2396
+ * Shared by the generator path and the batch plugin to avoid circular deps.
2397
+ */
2398
+ /**
2399
+ * Resolve a command string from the {@link ScriptsTable} table.
2400
+ * A script may be expressed as a string or an object with a `cmd` property.
2401
+ *
2402
+ * @param scripts - Optional scripts table.
2403
+ * @param command - User-provided command name or string.
2404
+ * @returns Resolved command string (falls back to the provided command).
2405
+ */
2406
+ const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
2407
+ ? scripts[command].cmd
2408
+ : (scripts?.[command] ?? command);
2409
+ /**
2410
+ * Resolve the shell setting for a given command:
2411
+ * - If the script entry is an object, prefer its `shell` override.
2412
+ * - Otherwise use the provided `shell` (string | boolean).
315
2413
  *
316
- * Adapter responsibility: pure mapping; no business logic.
2414
+ * @param scripts - Optional scripts table.
2415
+ * @param command - User-provided command name or string.
2416
+ * @param shell - Global shell preference (string | boolean).
317
2417
  */
2418
+ const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
2419
+ ? (scripts[command].shell ?? false)
2420
+ : (shell ?? false);
2421
+
318
2422
  const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
319
- /** Build a sanitized env for child processes from base + overlay. */
2423
+ /**
2424
+ * Build a sanitized environment object for spawning child processes.
2425
+ * Merges `base` and `overlay`, drops undefined values, and handles platform-specific
2426
+ * normalization (e.g. case-insensitivity on Windows).
2427
+ *
2428
+ * @param base - Base environment (usually `process.env`).
2429
+ * @param overlay - Environment variables to overlay.
2430
+ */
320
2431
  const buildSpawnEnv = (base, overlay) => {
321
2432
  const raw = {
322
2433
  ...(base ?? {}),
@@ -380,6 +2491,10 @@ const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
380
2491
  }
381
2492
  return { absRootPath, paths };
382
2493
  };
2494
+ /**
2495
+ * Execute a batch of commands across multiple directories.
2496
+ * Discovers targets via globs/rootPath and runs the command in each.
2497
+ */
383
2498
  const execShellCommandBatch = async ({ command, getDotenvCliOptions, dotenvEnv, globs, ignoreErrors, list, logger, pkgCwd, rootPath, shell, }) => {
384
2499
  const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
385
2500
  Boolean(getDotenvCliOptions?.capture);
@@ -390,7 +2505,7 @@ const execShellCommandBatch = async ({ command, getDotenvCliOptions, dotenvEnv,
390
2505
  }
391
2506
  const { absRootPath, paths } = await globPaths({
392
2507
  globs,
393
- logger,
2508
+ logger: logger,
394
2509
  rootPath,
395
2510
  // exactOptionalPropertyTypes: only include when defined
396
2511
  ...(pkgCwd !== undefined ? { pkgCwd } : {}),
@@ -430,22 +2545,8 @@ const execShellCommandBatch = async ({ command, getDotenvCliOptions, dotenvEnv,
430
2545
  const hasCmd = (typeof command === 'string' && command.length > 0) ||
431
2546
  (Array.isArray(command) && command.length > 0);
432
2547
  if (hasCmd) {
433
- // Compose child env overlay from dotenv (drop undefined) and merged options
434
- const overlay = {};
435
- if (dotenvEnv) {
436
- for (const [k, v] of Object.entries(dotenvEnv)) {
437
- if (typeof v === 'string')
438
- overlay[k] = v;
439
- }
440
- }
441
- if (getDotenvCliOptions !== undefined) {
442
- try {
443
- overlay.getDotenvCliOptions = JSON.stringify(getDotenvCliOptions);
444
- }
445
- catch {
446
- // best-effort: omit if serialization fails
447
- }
448
- }
2548
+ // Compose child env overlay (dotenv + nested bag)
2549
+ const overlay = composeNestedEnv(getDotenvCliOptions ?? {}, dotenvEnv ?? {});
449
2550
  await runCommand(command, shell, {
450
2551
  cwd: path,
451
2552
  env: buildSpawnEnv(process.env, overlay),
@@ -468,261 +2569,225 @@ const execShellCommandBatch = async ({ command, getDotenvCliOptions, dotenvEnv,
468
2569
  };
469
2570
 
470
2571
  /**
471
- * Batch services (neutral): resolve command and shell settings.
472
- * Shared by the generator path and the batch plugin to avoid circular deps.
473
- */
474
- /**
475
- * Resolve a command string from the {@link Scripts} table.
476
- * A script may be expressed as a string or an object with a `cmd` property.
477
- *
478
- * @param scripts - Optional scripts table.
479
- * @param command - User-provided command name or string.
480
- * @returns Resolved command string (falls back to the provided command).
481
- */
482
- const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
483
- ? scripts[command].cmd
484
- : (scripts?.[command] ?? command);
485
- /**
486
- * Resolve the shell setting for a given command:
487
- * - If the script entry is an object, prefer its `shell` override.
488
- * - Otherwise use the provided `shell` (string | boolean).
489
- *
490
- * @param scripts - Optional scripts table.
491
- * @param command - User-provided command name or string.
492
- * @param shell - Global shell preference (string | boolean).
2572
+ * Attach the default "cmd" subcommand action with contextual typing.
493
2573
  */
494
- const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
495
- ? (scripts[command].shell ?? false)
496
- : (shell ?? false);
2574
+ const attachDefaultCmdAction = (plugin, cli, batchCmd, pluginOpts, cmd) => {
2575
+ cmd.action(async (commandParts, _subOpts, thisCommand) => {
2576
+ const mergedBag = readMergedOptions(batchCmd);
2577
+ const logger = mergedBag.logger;
2578
+ // Guard: when invoked without positional args (e.g., `batch --list`), defer to parent.
2579
+ const args = commandParts.map(String);
2580
+ // Access merged per-plugin config from host context (if any).
2581
+ const cfg = plugin.readConfig(cli);
2582
+ const dotenvEnv = cli.getCtx().dotenv;
2583
+ // Resolve batch flags from the parent (batch) command.
2584
+ const gSrc = (() => {
2585
+ // Safely retrieve merged parent flags (prefer optsWithGlobals when present)
2586
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2587
+ // @ts-ignore - accessed reflectively; contextual typing supplied by Commander
2588
+ const maybe = thisCommand.optsWithGlobals;
2589
+ return typeof maybe === 'function' ? maybe.call(thisCommand) : {};
2590
+ })();
2591
+ const g = gSrc;
2592
+ const ignoreErrors = Boolean(g.ignoreErrors);
2593
+ const globs = typeof g.globs === 'string'
2594
+ ? g.globs
2595
+ : typeof cfg.globs === 'string'
2596
+ ? cfg.globs
2597
+ : '*';
2598
+ const pkgCwd = g.pkgCwd !== undefined ? g.pkgCwd : Boolean(cfg.pkgCwd);
2599
+ const rootPath = typeof g.rootPath === 'string'
2600
+ ? g.rootPath
2601
+ : typeof cfg.rootPath === 'string'
2602
+ ? cfg.rootPath
2603
+ : './';
2604
+ // Resolve scripts/shell with precedence:
2605
+ // plugin opts → plugin config → merged root CLI options
2606
+ const scripts = pluginOpts.scripts ?? cfg.scripts ?? mergedBag.scripts ?? undefined;
2607
+ const shell = pluginOpts.shell ?? cfg.shell ?? mergedBag.shell;
2608
+ // If no positional args were given, bridge to --command/--list paths here.
2609
+ if (args.length === 0) {
2610
+ const commandOpt = typeof g.command === 'string' ? g.command : undefined;
2611
+ if (typeof commandOpt === 'string') {
2612
+ await execShellCommandBatch({
2613
+ command: resolveCommand(scripts, commandOpt),
2614
+ dotenvEnv,
2615
+ globs,
2616
+ ignoreErrors,
2617
+ list: false,
2618
+ logger,
2619
+ ...(pkgCwd ? { pkgCwd } : {}),
2620
+ rootPath,
2621
+ shell: resolveShell(scripts, commandOpt, shell),
2622
+ });
2623
+ return;
2624
+ }
2625
+ if (g.list) {
2626
+ // Resolve shell fallback to a concrete value (never undefined)
2627
+ const rootShell = mergedBag.shell;
2628
+ const listShell = shell !== undefined
2629
+ ? shell
2630
+ : rootShell !== undefined
2631
+ ? rootShell
2632
+ : false;
2633
+ await execShellCommandBatch({
2634
+ globs,
2635
+ ignoreErrors,
2636
+ list: true,
2637
+ logger,
2638
+ ...(pkgCwd ? { pkgCwd } : {}),
2639
+ rootPath,
2640
+ shell: listShell,
2641
+ });
2642
+ return;
2643
+ }
2644
+ {
2645
+ logger.error('No command provided. Use --command or --list.');
2646
+ }
2647
+ process.exit(0);
2648
+ }
2649
+ // Note: Local "-l/--list" tokens are no longer interpreted here.
2650
+ // List-only mode must be requested via the parent flag ("batch -l ...").
2651
+ // Join positional args as the command to execute.
2652
+ const input = args.map(String).join(' ');
2653
+ // Optional: round-trip parent merged options if present (shipped CLI).
2654
+ const envBag = batchCmd.parent?.getDotenvCliOptions;
2655
+ const scriptsExec = scripts ?? mergedBag.scripts ?? undefined;
2656
+ const shellExec = shell ?? mergedBag.shell;
2657
+ const resolved = resolveCommand(scriptsExec, input);
2658
+ const shellSetting = resolveShell(scriptsExec, input, shellExec);
2659
+ // Preserve argv array only for shell-off Node -e snippets to avoid
2660
+ // lossy re-tokenization (Windows/PowerShell quoting). For simple
2661
+ // commands (e.g., "echo OK") keep string form to satisfy unit tests.
2662
+ let commandArg = resolved;
2663
+ if (shellSetting === false && resolved === input) {
2664
+ const preserved = maybePreserveNodeEvalArgv(args);
2665
+ if (preserved !== args)
2666
+ commandArg = preserved;
2667
+ }
2668
+ await execShellCommandBatch({
2669
+ command: commandArg,
2670
+ dotenvEnv,
2671
+ ...(envBag ? { getDotenvCliOptions: envBag } : {}),
2672
+ globs,
2673
+ ignoreErrors,
2674
+ list: false,
2675
+ logger,
2676
+ ...(pkgCwd ? { pkgCwd } : {}),
2677
+ rootPath,
2678
+ shell: shellSetting,
2679
+ });
2680
+ });
2681
+ };
497
2682
 
498
2683
  /**
499
- * Build the default "cmd" subcommand action for the batch plugin.
500
- * Mirrors the original inline implementation with identical behavior.
501
- */
502
- const buildDefaultCmdAction = (plugin, cli, batchCmd, opts) => async (commandParts, _subOpts, _thisCommand) => {
503
- const loggerLocal = opts.logger ?? console;
504
- // Guard: when invoked without positional args (e.g., `batch --list`),
505
- // defer entirely to the parent action handler.
506
- const argsRaw = Array.isArray(commandParts)
507
- ? commandParts
508
- : [];
509
- const localList = argsRaw.includes('-l') || argsRaw.includes('--list');
510
- const args = localList
511
- ? argsRaw.filter((t) => t !== '-l' && t !== '--list')
512
- : argsRaw;
513
- // Access merged per-plugin config from host context (if any).
514
- const cfg = plugin.readConfig(cli);
515
- const dotenvEnv = (cli.getCtx()?.dotenv ?? {});
516
- // Resolve batch flags from the captured parent (batch) command.
517
- const raw = batchCmd.opts();
518
- const listFromParent = !!raw.list;
519
- const ignoreErrors = !!raw.ignoreErrors;
520
- const globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
521
- const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
522
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
523
- // Resolve scripts/shell with precedence:
524
- // plugin opts plugin config merged root CLI options
525
- const mergedBag = ((batchCmd.parent ?? null)?.getDotenvCliOptions ?? {});
526
- const scripts = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
527
- const shell = opts.shell ?? cfg.shell ?? mergedBag.shell;
528
- // If no positional args were given, bridge to --command/--list paths here.
529
- if (args.length === 0) {
530
- const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
531
- if (typeof commandOpt === 'string') {
2684
+ * Attach the parent-level action for the batch plugin.
2685
+ * Handles parent flags (e.g. `getdotenv batch -l`) and delegates to the batch executor.
2686
+ */
2687
+ const attachParentInvoker = (plugin, cli, pluginOpts, parent) => {
2688
+ parent.action(async function (...args) {
2689
+ // Commander Unknown generics: [...unknown[], OptionValues, thisCommand]
2690
+ const thisCommand = args[args.length - 1];
2691
+ const opts = args.length >= 2
2692
+ ? args[args.length - 2]
2693
+ : {};
2694
+ // Read merged root options once and reuse across all code paths.
2695
+ const merged = readMergedOptions(thisCommand);
2696
+ const logger = merged.logger;
2697
+ // Ensure context exists (host preSubcommand on root creates if missing).
2698
+ const dotenvEnv = cli.getCtx().dotenv;
2699
+ const cfg = plugin.readConfig(cli);
2700
+ const commandOpt = typeof opts.command === 'string' ? opts.command : undefined;
2701
+ const ignoreErrors = Boolean(opts.ignoreErrors);
2702
+ let globs = typeof opts.globs === 'string' ? opts.globs : (cfg.globs ?? '*');
2703
+ const list = Boolean(opts.list);
2704
+ const pkgCwd = opts.pkgCwd !== undefined ? opts.pkgCwd : Boolean(cfg.pkgCwd);
2705
+ const rootPath = typeof opts.rootPath === 'string'
2706
+ ? opts.rootPath
2707
+ : (cfg.rootPath ?? './');
2708
+ // Treat parent positional tokens as the command when no explicit 'cmd' is used.
2709
+ const argsParent = (Array.isArray(args[0]) ? args[0] : []).map(String);
2710
+ // Root-merged bag for nested forwarding (single read above).
2711
+ const mergedBag = merged;
2712
+ if (argsParent.length > 0 && !list) {
2713
+ const input = argsParent.join(' ');
2714
+ const scriptsAll = pluginOpts.scripts ?? cfg.scripts ?? merged.scripts ?? undefined;
2715
+ const shellAll = pluginOpts.shell ?? cfg.shell ?? merged.shell;
2716
+ const resolved = resolveCommand(scriptsAll, input);
2717
+ const shellSetting = resolveShell(scriptsAll, input, shellAll);
2718
+ // Parent path: pass a string; executor handles shell-specific details.
2719
+ const commandArg = resolved;
532
2720
  await execShellCommandBatch({
533
- command: resolveCommand(scripts, commandOpt),
2721
+ command: commandArg,
534
2722
  dotenvEnv,
535
2723
  globs,
536
2724
  ignoreErrors,
537
2725
  list: false,
538
- logger: loggerLocal,
2726
+ logger,
539
2727
  ...(pkgCwd ? { pkgCwd } : {}),
540
2728
  rootPath,
541
- shell: resolveShell(scripts, commandOpt, shell),
2729
+ shell: shellSetting,
2730
+ getDotenvCliOptions: mergedBag,
542
2731
  });
543
2732
  return;
544
2733
  }
545
- if (raw.list || localList) {
546
- const shellBag = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
2734
+ // List-only (parent flag): merge extra positional tokens into globs when no --command is present.
2735
+ if (list && !commandOpt) {
2736
+ const extra = argsParent.join(' ').trim();
2737
+ if (extra.length > 0)
2738
+ globs = [globs, extra].filter(Boolean).join(' ');
2739
+ const shellMerged = pluginOpts.shell ?? cfg.shell ?? merged.shell ?? false;
547
2740
  await execShellCommandBatch({
548
2741
  globs,
549
2742
  ignoreErrors,
550
2743
  list: true,
551
- logger: loggerLocal,
2744
+ logger,
552
2745
  ...(pkgCwd ? { pkgCwd } : {}),
553
2746
  rootPath,
554
- shell: shell ?? shellBag.shell ?? false,
2747
+ shell: shellMerged,
2748
+ getDotenvCliOptions: mergedBag,
555
2749
  });
556
2750
  return;
557
2751
  }
558
- {
559
- const lr = loggerLocal;
560
- const emit = lr.error ?? lr.log;
561
- emit(`No command provided. Use --command or --list.`);
2752
+ if (!commandOpt && !list) {
2753
+ logger.error(`No command provided. Use --command or --list.`);
2754
+ process.exit(0);
562
2755
  }
563
- process.exit(0);
564
- }
565
- // If a local list flag was supplied with positional tokens (and no --command),
566
- // treat tokens as additional globs and execute list mode.
567
- if (localList && typeof raw.command !== 'string') {
568
- const extraGlobs = args.map(String).join(' ').trim();
569
- const mergedGlobs = [globs, extraGlobs].filter(Boolean).join(' ');
570
- const shellBag = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
571
- await execShellCommandBatch({
572
- globs: mergedGlobs,
573
- ignoreErrors,
574
- list: true,
575
- logger: loggerLocal,
576
- ...(pkgCwd ? { pkgCwd } : {}),
577
- rootPath,
578
- shell: shell ?? shellBag.shell ?? false,
579
- });
580
- return;
581
- }
582
- // If parent list flag is set and positional tokens are present (and no --command),
583
- // treat tokens as additional globs for list-only mode.
584
- if (listFromParent && args.length > 0 && typeof raw.command !== 'string') {
585
- const extra = args.map(String).join(' ').trim();
586
- const mergedGlobs = [globs, extra].filter(Boolean).join(' ');
587
- const mergedBag2 = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
588
- await execShellCommandBatch({
589
- globs: mergedGlobs,
590
- ignoreErrors,
591
- list: true,
592
- logger: loggerLocal,
593
- ...(pkgCwd ? { pkgCwd } : {}),
594
- rootPath,
595
- shell: (shell ?? mergedBag2.shell ?? false),
596
- });
597
- return;
598
- }
599
- // Join positional args as the command to execute.
600
- const input = args.map(String).join(' ');
601
- // Optional: round-trip parent merged options if present (shipped CLI).
602
- const envBag = (batchCmd.parent ?? undefined)?.getDotenvCliOptions;
603
- const mergedExec = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
604
- const scriptsExec = scripts ?? mergedExec.scripts;
605
- const shellExec = shell ?? mergedExec.shell;
606
- const resolved = resolveCommand(scriptsExec, input);
607
- const shellSetting = resolveShell(scriptsExec, input, shellExec);
608
- // Preserve argv array only for shell-off Node -e snippets to avoid
609
- // lossy re-tokenization (Windows/PowerShell quoting). For simple
610
- // commands (e.g., "echo OK") keep string form to satisfy unit tests.
611
- let commandArg = resolved;
612
- if (shellSetting === false && resolved === input) {
613
- const first = (args[0] ?? '').toLowerCase();
614
- const hasEval = args.includes('-e') || args.includes('--eval');
615
- if (first === 'node' && hasEval) {
616
- commandArg = args.map(String);
2756
+ if (typeof commandOpt === 'string') {
2757
+ const scriptsOpt = pluginOpts.scripts ?? cfg.scripts ?? merged.scripts ?? undefined;
2758
+ const shellOpt = pluginOpts.shell ?? cfg.shell ?? merged.shell;
2759
+ await execShellCommandBatch({
2760
+ command: resolveCommand(scriptsOpt, commandOpt),
2761
+ dotenvEnv,
2762
+ globs,
2763
+ ignoreErrors,
2764
+ list,
2765
+ logger,
2766
+ ...(pkgCwd ? { pkgCwd } : {}),
2767
+ rootPath,
2768
+ shell: resolveShell(scriptsOpt, commandOpt, shellOpt),
2769
+ getDotenvCliOptions: mergedBag,
2770
+ });
2771
+ return;
617
2772
  }
618
- }
619
- await execShellCommandBatch({
620
- command: commandArg,
621
- dotenvEnv,
622
- ...(envBag ? { getDotenvCliOptions: envBag } : {}),
623
- globs,
624
- ignoreErrors,
625
- list: false,
626
- logger: loggerLocal,
627
- ...(pkgCwd ? { pkgCwd } : {}),
628
- rootPath,
629
- shell: shellSetting,
630
- });
631
- };
632
-
633
- /**
634
- * Build the parent "batch" action handler (no explicit subcommand).
635
- */
636
- const buildParentAction = (plugin, cli, opts) => async (commandParts, thisCommand) => {
637
- const loggerLocal = opts.logger ?? console;
638
- // Ensure context exists (host preSubcommand on root creates if missing).
639
- const dotenvEnv = (cli.getCtx()?.dotenv ?? {});
640
- const cfg = plugin.readConfig(cli);
641
- const raw = thisCommand.opts();
642
- const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
643
- const ignoreErrors = !!raw.ignoreErrors;
644
- let globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
645
- const list = !!raw.list;
646
- const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
647
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
648
- // Treat parent positional tokens as the command when no explicit 'cmd' is used.
649
- const argsParent = Array.isArray(commandParts) ? commandParts : [];
650
- if (argsParent.length > 0 && !list) {
651
- const input = argsParent.map(String).join(' ');
652
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
653
- const scriptsAll = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
654
- const shellAll = opts.shell ?? cfg.shell ?? mergedBag.shell;
655
- const resolved = resolveCommand(scriptsAll, input);
656
- const shellSetting = resolveShell(scriptsAll, input, shellAll);
657
- // Parent path: pass a string; executor handles shell-specific details.
658
- const commandArg = resolved;
659
- await execShellCommandBatch({
660
- command: commandArg,
661
- dotenvEnv,
662
- globs,
663
- ignoreErrors,
664
- list: false,
665
- logger: loggerLocal,
666
- ...(pkgCwd ? { pkgCwd } : {}),
667
- rootPath,
668
- shell: shellSetting,
669
- });
670
- return;
671
- }
672
- // List-only: merge extra positional tokens into globs when no --command is present.
673
- if (list && argsParent.length > 0 && !commandOpt) {
674
- const extra = argsParent.map(String).join(' ').trim();
675
- if (extra.length > 0)
676
- globs = [globs, extra].filter(Boolean).join(' ');
677
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
678
- const shellMerged = opts.shell ?? cfg.shell ?? mergedBag.shell ?? false;
2773
+ // list only (explicit --list without --command)
2774
+ const shellOnly = pluginOpts.shell ?? cfg.shell ?? merged.shell ?? false;
679
2775
  await execShellCommandBatch({
680
2776
  globs,
681
2777
  ignoreErrors,
682
2778
  list: true,
683
- logger: loggerLocal,
684
- ...(pkgCwd ? { pkgCwd } : {}),
685
- rootPath,
686
- shell: shellMerged,
687
- });
688
- return;
689
- }
690
- if (!commandOpt && !list) {
691
- loggerLocal.error(`No command provided. Use --command or --list.`);
692
- process.exit(0);
693
- }
694
- if (typeof commandOpt === 'string') {
695
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
696
- const scriptsOpt = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
697
- const shellOpt = opts.shell ?? cfg.shell ?? mergedBag.shell;
698
- await execShellCommandBatch({
699
- command: resolveCommand(scriptsOpt, commandOpt),
700
- dotenvEnv,
701
- globs,
702
- ignoreErrors,
703
- list,
704
- logger: loggerLocal,
2779
+ logger,
705
2780
  ...(pkgCwd ? { pkgCwd } : {}),
706
2781
  rootPath,
707
- shell: resolveShell(scriptsOpt, commandOpt, shellOpt),
2782
+ shell: shellOnly,
2783
+ getDotenvCliOptions: mergedBag,
708
2784
  });
709
- return;
710
- }
711
- // list only (explicit --list without --command)
712
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
713
- const shellOnly = opts.shell ?? cfg.shell ?? mergedBag.shell ?? false;
714
- await execShellCommandBatch({
715
- globs,
716
- ignoreErrors,
717
- list: true,
718
- logger: loggerLocal,
719
- ...(pkgCwd ? { pkgCwd } : {}),
720
- rootPath,
721
- shell: shellOnly,
722
2785
  });
723
2786
  };
724
2787
 
725
- // Per-plugin config schema (optional fields; used as defaults).
2788
+ /**
2789
+ * Zod schema for a single script entry (string or object).
2790
+ */
726
2791
  const ScriptSchema = z.union([
727
2792
  z.string(),
728
2793
  z.object({
@@ -730,6 +2795,9 @@ const ScriptSchema = z.union([
730
2795
  shell: z.union([z.string(), z.boolean()]).optional(),
731
2796
  }),
732
2797
  ]);
2798
+ /**
2799
+ * Zod schema for batch plugin configuration.
2800
+ */
733
2801
  const BatchConfigSchema = z.object({
734
2802
  scripts: z.record(z.string(), ScriptSchema).optional(),
735
2803
  shell: z.union([z.string(), z.boolean()]).optional(),
@@ -738,26 +2806,30 @@ const BatchConfigSchema = z.object({
738
2806
  pkgCwd: z.boolean().optional(),
739
2807
  });
740
2808
 
2809
+ /**
2810
+ * @packageDocumentation
2811
+ * Batch plugin subpath. Provides the `batch` command for executing a command
2812
+ * across multiple working directories using glob discovery, with optional list
2813
+ * mode and script‑aware shell resolution.
2814
+ */
741
2815
  /**
742
2816
  * Batch plugin for the GetDotenv CLI host.
743
2817
  *
744
2818
  * Mirrors the legacy batch subcommand behavior without altering the shipped CLI.
745
2819
  * Options:
746
2820
  * - scripts/shell: used to resolve command and shell behavior per script or global default.
747
- * - logger: defaults to console.
748
2821
  */
749
2822
  const batchPlugin = (opts = {}) => {
750
2823
  const plugin = definePlugin({
751
- id: 'batch',
2824
+ ns: 'batch',
752
2825
  // Host validates this when config-loader is enabled; plugins may also
753
2826
  // re-validate at action time as a safety belt.
754
2827
  configSchema: BatchConfigSchema,
755
2828
  setup(cli) {
756
- const ns = cli.ns('batch');
757
- const batchCmd = ns; // capture the parent "batch" command for default-subcommand context
758
- const pluginId = 'batch';
759
- const GROUP = `plugin:${pluginId}`;
760
- ns.description('Batch command execution across multiple working directories.')
2829
+ const batchCmd = cli; // mount provided by host
2830
+ const GROUP = `plugin:${cli.name()}`;
2831
+ batchCmd
2832
+ .description('Batch command execution across multiple working directories.')
761
2833
  .enablePositionalOptions()
762
2834
  .passThroughOptions()
763
2835
  // Dynamic help: show effective defaults from the merged/interpolated plugin config slice.
@@ -779,15 +2851,19 @@ const batchPlugin = (opts = {}) => {
779
2851
  .option('-c, --command <string>', 'command executed according to the base shell resolution')
780
2852
  .option('-l, --list', 'list working directories without executing command')
781
2853
  .option('-e, --ignore-errors', 'ignore errors and continue with next path')
782
- .argument('[command...]')
783
- .addCommand(new Command()
2854
+ .argument('[command...]');
2855
+ // Default subcommand "cmd" with contextual typing for args/opts
2856
+ const cmdSub = new Command()
784
2857
  .name('cmd')
785
2858
  .description('execute command, conflicts with --command option (default subcommand)')
786
2859
  .enablePositionalOptions()
787
2860
  .passThroughOptions()
788
- .argument('[command...]')
789
- .action(buildDefaultCmdAction(plugin, cli, batchCmd, opts)), { isDefault: true })
790
- .action(buildParentAction(plugin, cli, opts));
2861
+ .argument('[command...]');
2862
+ attachDefaultCmdAction(plugin, cli, batchCmd, opts, cmdSub);
2863
+ batchCmd.addCommand(cmdSub, { isDefault: true });
2864
+ // Parent invoker (unified naming)
2865
+ attachParentInvoker(plugin, cli, opts, batchCmd);
2866
+ return undefined;
791
2867
  },
792
2868
  });
793
2869
  return plugin;