@karmaniverous/get-dotenv 5.2.1 → 5.2.3

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.
@@ -0,0 +1,2498 @@
1
+ import { Command, Option } from 'commander';
2
+ import { execa, execaCommand } from 'execa';
3
+ import fs from 'fs-extra';
4
+ import { packageDirectory } from 'package-directory';
5
+ import url, { fileURLToPath, pathToFileURL } from 'url';
6
+ import path, { join, extname } from 'path';
7
+ import { z } from 'zod';
8
+ import YAML from 'yaml';
9
+ import { nanoid } from 'nanoid';
10
+ import { parse } from 'dotenv';
11
+ import { createHash } from 'crypto';
12
+
13
+ // Minimal tokenizer for shell-off execution:
14
+ // Splits by whitespace while preserving quoted segments (single or double quotes).
15
+ const tokenize = (command) => {
16
+ const out = [];
17
+ let cur = '';
18
+ let quote = null;
19
+ for (let i = 0; i < command.length; i++) {
20
+ const c = command.charAt(i);
21
+ if (quote) {
22
+ if (c === quote) {
23
+ // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
24
+ // "" -> " and '' -> '
25
+ const next = command.charAt(i + 1);
26
+ if (next === quote) {
27
+ cur += quote;
28
+ i += 1; // skip the second quote
29
+ }
30
+ else {
31
+ // end of quoted segment
32
+ quote = null;
33
+ }
34
+ }
35
+ else {
36
+ cur += c;
37
+ }
38
+ }
39
+ else {
40
+ if (c === '"' || c === "'") {
41
+ quote = c;
42
+ }
43
+ else if (/\s/.test(c)) {
44
+ if (cur) {
45
+ out.push(cur);
46
+ cur = '';
47
+ }
48
+ }
49
+ else {
50
+ cur += c;
51
+ }
52
+ }
53
+ }
54
+ if (cur)
55
+ out.push(cur);
56
+ return out;
57
+ };
58
+
59
+ const dbg$1 = (...args) => {
60
+ if (process.env.GETDOTENV_DEBUG) {
61
+ // Use stderr to avoid interfering with stdout assertions
62
+ console.error('[getdotenv:run]', ...args);
63
+ }
64
+ };
65
+ // Strip repeated symmetric outer quotes (single or double) until stable.
66
+ // This is safe for argv arrays passed to execa (no quoting needed) and avoids
67
+ // passing quote characters through to Node (e.g., for `node -e "<code>"`).
68
+ // Handles stacked quotes from shells like PowerShell: """code""" -> code.
69
+ const stripOuterQuotes = (s) => {
70
+ let out = s;
71
+ // Repeatedly trim only when the entire string is wrapped in matching quotes.
72
+ // Stop as soon as the ends are asymmetric or no quotes remain.
73
+ while (out.length >= 2) {
74
+ const a = out.charAt(0);
75
+ const b = out.charAt(out.length - 1);
76
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
77
+ if (!symmetric)
78
+ break;
79
+ out = out.slice(1, -1);
80
+ }
81
+ return out;
82
+ };
83
+ // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
84
+ // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
85
+ const sanitizeEnv = (env) => {
86
+ if (!env)
87
+ return undefined;
88
+ const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
89
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
90
+ };
91
+ const runCommand = async (command, shell, opts) => {
92
+ if (shell === false) {
93
+ let file;
94
+ let args = [];
95
+ if (Array.isArray(command)) {
96
+ file = command[0];
97
+ args = command.slice(1).map(stripOuterQuotes);
98
+ }
99
+ else {
100
+ const tokens = tokenize(command);
101
+ file = tokens[0];
102
+ args = tokens.slice(1);
103
+ }
104
+ if (!file)
105
+ return 0;
106
+ dbg$1('exec (plain)', { file, args, stdio: opts.stdio });
107
+ // Build options without injecting undefined properties (exactOptionalPropertyTypes).
108
+ const envSan = sanitizeEnv(opts.env);
109
+ const plainOpts = {};
110
+ if (opts.cwd !== undefined)
111
+ plainOpts.cwd = opts.cwd;
112
+ if (envSan !== undefined)
113
+ plainOpts.env = envSan;
114
+ if (opts.stdio !== undefined)
115
+ plainOpts.stdio = opts.stdio;
116
+ const result = await execa(file, args, plainOpts);
117
+ if (opts.stdio === 'pipe' && result.stdout) {
118
+ process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
119
+ }
120
+ const exit = result?.exitCode;
121
+ dbg$1('exit (plain)', { exitCode: exit });
122
+ return typeof exit === 'number' ? exit : Number.NaN;
123
+ }
124
+ else {
125
+ const commandStr = Array.isArray(command) ? command.join(' ') : command;
126
+ dbg$1('exec (shell)', {
127
+ shell: typeof shell === 'string' ? shell : 'custom',
128
+ stdio: opts.stdio,
129
+ command: commandStr,
130
+ });
131
+ const envSan = sanitizeEnv(opts.env);
132
+ const shellOpts = { shell };
133
+ if (opts.cwd !== undefined)
134
+ shellOpts.cwd = opts.cwd;
135
+ if (envSan !== undefined)
136
+ shellOpts.env = envSan;
137
+ if (opts.stdio !== undefined)
138
+ shellOpts.stdio = opts.stdio;
139
+ const result = await execaCommand(commandStr, shellOpts);
140
+ const out = result?.stdout;
141
+ if (opts.stdio === 'pipe' && out) {
142
+ process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
143
+ }
144
+ const exit = result?.exitCode;
145
+ dbg$1('exit (shell)', { exitCode: exit });
146
+ return typeof exit === 'number' ? exit : Number.NaN;
147
+ }
148
+ };
149
+
150
+ const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
151
+ /** Build a sanitized env for child processes from base + overlay. */
152
+ const buildSpawnEnv = (base, overlay) => {
153
+ const raw = {
154
+ ...(base ?? {}),
155
+ ...(overlay ?? {}),
156
+ };
157
+ // Drop undefined first
158
+ const entries = Object.entries(dropUndefined(raw));
159
+ if (process.platform === 'win32') {
160
+ // Windows: keys are case-insensitive; collapse duplicates
161
+ const byLower = new Map();
162
+ for (const [k, v] of entries) {
163
+ byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
164
+ }
165
+ const out = {};
166
+ for (const [, [k, v]] of byLower)
167
+ out[k] = v;
168
+ // HOME fallback from USERPROFILE (common expectation)
169
+ if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
170
+ const up = out['USERPROFILE'];
171
+ if (typeof up === 'string' && up.length > 0)
172
+ out['HOME'] = up;
173
+ }
174
+ // Normalize TMP/TEMP coherence (pick any present; reflect to both)
175
+ const tmp = out['TMP'] ?? out['TEMP'];
176
+ if (typeof tmp === 'string' && tmp.length > 0) {
177
+ out['TMP'] = tmp;
178
+ out['TEMP'] = tmp;
179
+ }
180
+ return out;
181
+ }
182
+ // POSIX: keep keys as-is
183
+ const out = Object.fromEntries(entries);
184
+ // Ensure TMPDIR exists when any temp key is present (best-effort)
185
+ const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
186
+ if (typeof tmpdir === 'string' && tmpdir.length > 0) {
187
+ out['TMPDIR'] = tmpdir;
188
+ }
189
+ return out;
190
+ };
191
+
192
+ /**
193
+ * Define a GetDotenv CLI plugin with compositional helpers.
194
+ *
195
+ * @example
196
+ * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
197
+ * .use(childA)
198
+ * .use(childB);
199
+ */
200
+ const definePlugin = (spec) => {
201
+ const { children = [], ...rest } = spec;
202
+ const plugin = {
203
+ ...rest,
204
+ children: [...children],
205
+ use(child) {
206
+ this.children.push(child);
207
+ return this;
208
+ },
209
+ };
210
+ return plugin;
211
+ };
212
+
213
+ /** src/diagnostics/entropy.ts
214
+ * Entropy diagnostics (presentation-only).
215
+ * - Gated by min length and printable ASCII.
216
+ * - Warn once per key per run when bits/char \>= threshold.
217
+ * - Supports whitelist patterns to suppress known-noise keys.
218
+ */
219
+ const warned = new Set();
220
+ const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
221
+ const compile$1 = (patterns) => (patterns ?? []).map((p) => new RegExp(p, 'i'));
222
+ const whitelisted = (key, regs) => regs.some((re) => re.test(key));
223
+ const shannonBitsPerChar = (s) => {
224
+ const freq = new Map();
225
+ for (const ch of s)
226
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
227
+ const n = s.length;
228
+ let h = 0;
229
+ for (const c of freq.values()) {
230
+ const p = c / n;
231
+ h -= p * Math.log2(p);
232
+ }
233
+ return h;
234
+ };
235
+ /**
236
+ * Maybe emit a one-line entropy warning for a key.
237
+ * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
238
+ */
239
+ const maybeWarnEntropy = (key, value, origin, opts, emit) => {
240
+ if (!opts || opts.warnEntropy === false)
241
+ return;
242
+ if (warned.has(key))
243
+ return;
244
+ const v = value ?? '';
245
+ const minLen = Math.max(0, opts.entropyMinLength ?? 16);
246
+ const threshold = opts.entropyThreshold ?? 3.8;
247
+ if (v.length < minLen)
248
+ return;
249
+ if (!isPrintableAscii(v))
250
+ return;
251
+ const wl = compile$1(opts.entropyWhitelist);
252
+ if (whitelisted(key, wl))
253
+ return;
254
+ const bpc = shannonBitsPerChar(v);
255
+ if (bpc >= threshold) {
256
+ warned.add(key);
257
+ emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
258
+ }
259
+ };
260
+
261
+ const DEFAULT_PATTERNS = [
262
+ '\\bsecret\\b',
263
+ '\\btoken\\b',
264
+ '\\bpass(word)?\\b',
265
+ '\\bapi[_-]?key\\b',
266
+ '\\bkey\\b',
267
+ ];
268
+ const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
269
+ const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
270
+ const MASK = '[redacted]';
271
+ /**
272
+ * Produce a shallow redacted copy of an env-like object for display.
273
+ */
274
+ const redactObject = (obj, opts) => {
275
+ if (!opts?.redact)
276
+ return { ...obj };
277
+ const regs = compile(opts.redactPatterns);
278
+ const out = {};
279
+ for (const [k, v] of Object.entries(obj)) {
280
+ out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
281
+ }
282
+ return out;
283
+ };
284
+ /**
285
+ * Utility to redact three related displayed values (parent/dotenv/final)
286
+ * consistently for trace lines.
287
+ */
288
+ const redactTriple = (key, triple, opts) => {
289
+ if (!opts?.redact)
290
+ return triple;
291
+ const regs = compile(opts.redactPatterns);
292
+ const maskIf = (v) => (v && shouldRedactKey(key, regs) ? MASK : v);
293
+ const out = {};
294
+ const p = maskIf(triple.parent);
295
+ const d = maskIf(triple.dotenv);
296
+ const f = maskIf(triple.final);
297
+ if (p !== undefined)
298
+ out.parent = p;
299
+ if (d !== undefined)
300
+ out.dotenv = d;
301
+ if (f !== undefined)
302
+ out.final = f;
303
+ return out;
304
+ };
305
+
306
+ /**
307
+ * Batch services (neutral): resolve command and shell settings.
308
+ * Shared by the generator path and the batch plugin to avoid circular deps.
309
+ */
310
+ /**
311
+ * Resolve a command string from the {@link Scripts} table.
312
+ * A script may be expressed as a string or an object with a `cmd` property.
313
+ *
314
+ * @param scripts - Optional scripts table.
315
+ * @param command - User-provided command name or string.
316
+ * @returns Resolved command string (falls back to the provided command).
317
+ */
318
+ const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
319
+ ? scripts[command].cmd
320
+ : (scripts?.[command] ?? command);
321
+ /**
322
+ * Resolve the shell setting for a given command:
323
+ * - If the script entry is an object, prefer its `shell` override.
324
+ * - Otherwise use the provided `shell` (string | boolean).
325
+ *
326
+ * @param scripts - Optional scripts table.
327
+ * @param command - User-provided command name or string.
328
+ * @param shell - Global shell preference (string | boolean).
329
+ */
330
+ const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
331
+ ? (scripts[command].shell ?? false)
332
+ : (shell ?? false);
333
+
334
+ // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
335
+ const baseRootOptionDefaults = {
336
+ dotenvToken: '.env',
337
+ loadProcess: true,
338
+ logger: console,
339
+ // Diagnostics defaults
340
+ warnEntropy: true,
341
+ entropyThreshold: 3.8,
342
+ entropyMinLength: 16,
343
+ entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
344
+ paths: './',
345
+ pathsDelimiter: ' ',
346
+ privateToken: 'local',
347
+ scripts: {
348
+ 'git-status': {
349
+ cmd: 'git branch --show-current && git status -s -u',
350
+ shell: true,
351
+ },
352
+ },
353
+ shell: true,
354
+ vars: '',
355
+ varsAssignor: '=',
356
+ varsDelimiter: ' ',
357
+ // tri-state flags default to unset unless explicitly provided
358
+ // (debug/log/exclude* resolved via flag utils)
359
+ };
360
+
361
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
362
+
363
+ /** @internal */
364
+ const isPlainObject$1 = (value) => value !== null &&
365
+ typeof value === 'object' &&
366
+ Object.getPrototypeOf(value) === Object.prototype;
367
+ const mergeInto = (target, source) => {
368
+ for (const [key, sVal] of Object.entries(source)) {
369
+ if (sVal === undefined)
370
+ continue; // do not overwrite with undefined
371
+ const tVal = target[key];
372
+ if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
373
+ target[key] = mergeInto({ ...tVal }, sVal);
374
+ }
375
+ else if (isPlainObject$1(sVal)) {
376
+ target[key] = mergeInto({}, sVal);
377
+ }
378
+ else {
379
+ target[key] = sVal;
380
+ }
381
+ }
382
+ return target;
383
+ };
384
+ /**
385
+ * Perform a deep defaults-style merge across plain objects. *
386
+ * - Only merges plain objects (prototype === Object.prototype).
387
+ * - Arrays and non-objects are replaced, not merged.
388
+ * - `undefined` values are ignored and do not overwrite prior values.
389
+ *
390
+ * @typeParam T - The resulting shape after merging all layers.
391
+ * @param layers - Zero or more partial layers in ascending precedence order.
392
+ * @returns The merged object typed as {@link T}.
393
+ *
394
+ * @example
395
+ * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
396
+ * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
397
+ */
398
+ const defaultsDeep = (...layers) => {
399
+ const result = layers
400
+ .filter(Boolean)
401
+ .reduce((acc, layer) => mergeInto(acc, layer), {});
402
+ return result;
403
+ };
404
+
405
+ // src/GetDotenvOptions.ts
406
+ const getDotenvOptionsFilename = 'getdotenv.config.json';
407
+ /**
408
+ * Converts programmatic CLI options to `getDotenv` options. *
409
+ * @param cliOptions - CLI options. Defaults to `{}`.
410
+ *
411
+ * @returns `getDotenv` options.
412
+ */
413
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
414
+ /**
415
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
416
+ *
417
+ * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
418
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
419
+ * - Drops CLI-only keys that have no programmatic equivalent.
420
+ *
421
+ * @remarks
422
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
423
+ */
424
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
425
+ // Create a shallow copy then delete optional CLI-only keys if present.
426
+ const restObj = { ...rest };
427
+ delete restObj.debug;
428
+ delete restObj.scripts;
429
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
430
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
431
+ let parsedVars;
432
+ if (typeof vars === 'string') {
433
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
434
+ ? RegExp(varsAssignorPattern)
435
+ : (varsAssignor ?? '=')));
436
+ parsedVars = Object.fromEntries(kvPairs);
437
+ }
438
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
439
+ // Keep only string or undefined values to match ProcessEnv.
440
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
441
+ parsedVars = Object.fromEntries(entries);
442
+ }
443
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
444
+ // expectations and the compat test assertions.
445
+ if (parsedVars) {
446
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
447
+ }
448
+ // Tolerate paths as either a delimited string or string[]
449
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
450
+ // under the RootOptionsShape (which declares paths as string | undefined).
451
+ const pathsAny = paths;
452
+ const pathsOut = Array.isArray(pathsAny)
453
+ ? pathsAny.filter((p) => typeof p === 'string')
454
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
455
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
456
+ return {
457
+ ...restObj,
458
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
459
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
460
+ };
461
+ };
462
+ const resolveGetDotenvOptions = async (customOptions) => {
463
+ /**
464
+ * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
465
+ *
466
+ * 1. Base defaults derived from the CLI generator defaults
467
+ * ({@link baseGetDotenvCliOptions}).
468
+ * 2. Local project overrides from a `getdotenv.config.json` in the nearest
469
+ * package root (if present).
470
+ * 3. The provided {@link customOptions}.
471
+ *
472
+ * The result preserves explicit empty values and drops only `undefined`.
473
+ *
474
+ * @returns Fully-resolved {@link GetDotenvOptions}.
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const options = await resolveGetDotenvOptions({ env: 'dev' });
479
+ * ```
480
+ */
481
+ const localPkgDir = await packageDirectory();
482
+ const localOptionsPath = localPkgDir
483
+ ? join(localPkgDir, getDotenvOptionsFilename)
484
+ : undefined;
485
+ const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
486
+ ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
487
+ : {});
488
+ // Merge order: base < local < custom (custom has highest precedence)
489
+ const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
490
+ const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
491
+ const result = defaultsDeep(defaultsFromCli, customOptions);
492
+ return {
493
+ ...result, // Keep explicit empty strings/zeros; drop only undefined
494
+ vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
495
+ };
496
+ };
497
+
498
+ /**
499
+ * Zod schemas for programmatic GetDotenv options.
500
+ *
501
+ * NOTE: These schemas are introduced without wiring to avoid behavior changes.
502
+ * Legacy paths continue to use existing types/logic. The new plugin host will
503
+ * use these schemas in strict mode; legacy paths will adopt them in warn mode
504
+ * later per the staged plan.
505
+ */
506
+ // Minimal process env representation: string values or undefined to indicate "unset".
507
+ const processEnvSchema = z.record(z.string(), z.string().optional());
508
+ // RAW: all fields optional — undefined means "inherit" from lower layers.
509
+ const getDotenvOptionsSchemaRaw = z.object({
510
+ defaultEnv: z.string().optional(),
511
+ dotenvToken: z.string().optional(),
512
+ dynamicPath: z.string().optional(),
513
+ // Dynamic map is intentionally wide for now; refine once sources are normalized.
514
+ dynamic: z.record(z.string(), z.unknown()).optional(),
515
+ env: z.string().optional(),
516
+ excludeDynamic: z.boolean().optional(),
517
+ excludeEnv: z.boolean().optional(),
518
+ excludeGlobal: z.boolean().optional(),
519
+ excludePrivate: z.boolean().optional(),
520
+ excludePublic: z.boolean().optional(),
521
+ loadProcess: z.boolean().optional(),
522
+ log: z.boolean().optional(),
523
+ outputPath: z.string().optional(),
524
+ paths: z.array(z.string()).optional(),
525
+ privateToken: z.string().optional(),
526
+ vars: processEnvSchema.optional(),
527
+ // Host-only feature flag: guarded integration of config loader/overlay
528
+ useConfigLoader: z.boolean().optional(),
529
+ });
530
+ // RESOLVED: service-boundary contract (post-inheritance).
531
+ // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
532
+ const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
533
+
534
+ /**
535
+ * Zod schemas for configuration files discovered by the new loader.
536
+ *
537
+ * Notes:
538
+ * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
539
+ * - RESOLVED: normalized shapes (paths always string[]).
540
+ * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
541
+ */
542
+ // String-only env value map
543
+ const stringMap = z.record(z.string(), z.string());
544
+ const envStringMap = z.record(z.string(), stringMap);
545
+ // Allow string[] or single string for "paths" in RAW; normalize later.
546
+ const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
547
+ const getDotenvConfigSchemaRaw = z.object({
548
+ dotenvToken: z.string().optional(),
549
+ privateToken: z.string().optional(),
550
+ paths: rawPathsSchema,
551
+ loadProcess: z.boolean().optional(),
552
+ log: z.boolean().optional(),
553
+ shell: z.union([z.string(), z.boolean()]).optional(),
554
+ scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
555
+ requiredKeys: z.array(z.string()).optional(),
556
+ schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
557
+ vars: stringMap.optional(), // public, global
558
+ envVars: envStringMap.optional(), // public, per-env
559
+ // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
560
+ dynamic: z.unknown().optional(),
561
+ // Per-plugin config bag; validated by plugins/host when used.
562
+ plugins: z.record(z.string(), z.unknown()).optional(),
563
+ });
564
+ // Normalize paths to string[]
565
+ const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
566
+ const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
567
+ ...raw,
568
+ paths: normalizePaths(raw.paths),
569
+ }));
570
+
571
+ // Discovery candidates (first match wins per scope/privacy).
572
+ // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
573
+ const PUBLIC_FILENAMES = [
574
+ 'getdotenv.config.json',
575
+ 'getdotenv.config.yaml',
576
+ 'getdotenv.config.yml',
577
+ 'getdotenv.config.js',
578
+ 'getdotenv.config.mjs',
579
+ 'getdotenv.config.cjs',
580
+ 'getdotenv.config.ts',
581
+ 'getdotenv.config.mts',
582
+ 'getdotenv.config.cts',
583
+ ];
584
+ const LOCAL_FILENAMES = [
585
+ 'getdotenv.config.local.json',
586
+ 'getdotenv.config.local.yaml',
587
+ 'getdotenv.config.local.yml',
588
+ 'getdotenv.config.local.js',
589
+ 'getdotenv.config.local.mjs',
590
+ 'getdotenv.config.local.cjs',
591
+ 'getdotenv.config.local.ts',
592
+ 'getdotenv.config.local.mts',
593
+ 'getdotenv.config.local.cts',
594
+ ];
595
+ const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
596
+ const isJson = (p) => extname(p).toLowerCase() === '.json';
597
+ const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
598
+ // --- Internal JS/TS module loader helpers (default export) ---
599
+ const importDefault$1 = async (fileUrl) => {
600
+ const mod = (await import(fileUrl));
601
+ return mod.default;
602
+ };
603
+ const cacheName = (absPath, suffix) => {
604
+ // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
605
+ const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
606
+ return `${base}.${suffix}.mjs`;
607
+ };
608
+ const ensureDir = async (dir) => {
609
+ await fs.ensureDir(dir);
610
+ return dir;
611
+ };
612
+ const loadJsTsDefault = async (absPath) => {
613
+ const fileUrl = pathToFileURL(absPath).toString();
614
+ const ext = extname(absPath).toLowerCase();
615
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
616
+ return importDefault$1(fileUrl);
617
+ }
618
+ // Try direct import first in case a TS loader is active.
619
+ try {
620
+ const val = await importDefault$1(fileUrl);
621
+ if (val)
622
+ return val;
623
+ }
624
+ catch {
625
+ /* fallthrough */
626
+ }
627
+ // esbuild bundle to a temp ESM file
628
+ try {
629
+ const esbuild = (await import('esbuild'));
630
+ const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
631
+ const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
632
+ await esbuild.build({
633
+ entryPoints: [absPath],
634
+ bundle: true,
635
+ platform: 'node',
636
+ format: 'esm',
637
+ target: 'node20',
638
+ outfile,
639
+ sourcemap: false,
640
+ logLevel: 'silent',
641
+ });
642
+ return await importDefault$1(pathToFileURL(outfile).toString());
643
+ }
644
+ catch {
645
+ /* fallthrough to TS transpile */
646
+ }
647
+ // typescript.transpileModule simple transpile (single-file)
648
+ try {
649
+ const ts = (await import('typescript'));
650
+ const src = await fs.readFile(absPath, 'utf-8');
651
+ const out = ts.transpileModule(src, {
652
+ compilerOptions: {
653
+ module: 'ESNext',
654
+ target: 'ES2022',
655
+ moduleResolution: 'NodeNext',
656
+ },
657
+ }).outputText;
658
+ const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
659
+ const outfile = path.join(outDir, cacheName(absPath, 'ts'));
660
+ await fs.writeFile(outfile, out, 'utf-8');
661
+ return await importDefault$1(pathToFileURL(outfile).toString());
662
+ }
663
+ catch {
664
+ throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
665
+ }
666
+ };
667
+ /**
668
+ * Discover JSON/YAML config files in the packaged root and project root.
669
+ * Order: packaged public → project public → project local. */
670
+ const discoverConfigFiles = async (importMetaUrl) => {
671
+ const files = [];
672
+ // Packaged root via importMetaUrl (optional)
673
+ if (importMetaUrl) {
674
+ const fromUrl = fileURLToPath(importMetaUrl);
675
+ const packagedRoot = await packageDirectory({ cwd: fromUrl });
676
+ if (packagedRoot) {
677
+ for (const name of PUBLIC_FILENAMES) {
678
+ const p = join(packagedRoot, name);
679
+ if (await fs.pathExists(p)) {
680
+ files.push({ path: p, privacy: 'public', scope: 'packaged' });
681
+ break; // only one public file expected per scope
682
+ }
683
+ }
684
+ // By policy, packaged .local is not expected; skip even if present.
685
+ }
686
+ }
687
+ // Project root (from current working directory)
688
+ const projectRoot = await packageDirectory();
689
+ if (projectRoot) {
690
+ for (const name of PUBLIC_FILENAMES) {
691
+ const p = join(projectRoot, name);
692
+ if (await fs.pathExists(p)) {
693
+ files.push({ path: p, privacy: 'public', scope: 'project' });
694
+ break;
695
+ }
696
+ }
697
+ for (const name of LOCAL_FILENAMES) {
698
+ const p = join(projectRoot, name);
699
+ if (await fs.pathExists(p)) {
700
+ files.push({ path: p, privacy: 'local', scope: 'project' });
701
+ break;
702
+ }
703
+ }
704
+ }
705
+ return files;
706
+ };
707
+ /**
708
+ * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
709
+ * Validates with Zod RAW schema, then normalizes to RESOLVED.
710
+ *
711
+ * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
712
+ * For JS/TS: default export is loaded; "dynamic" is allowed.
713
+ */
714
+ const loadConfigFile = async (filePath) => {
715
+ let raw = {};
716
+ try {
717
+ const abs = path.resolve(filePath);
718
+ if (isJsOrTs(abs)) {
719
+ // JS/TS support: load default export via robust pipeline.
720
+ const mod = await loadJsTsDefault(abs);
721
+ raw = mod ?? {};
722
+ }
723
+ else {
724
+ const txt = await fs.readFile(abs, 'utf-8');
725
+ raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
726
+ }
727
+ }
728
+ catch (err) {
729
+ throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
730
+ }
731
+ // Validate RAW
732
+ const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
733
+ if (!parsed.success) {
734
+ const msgs = parsed.error.issues
735
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
736
+ .join('\n');
737
+ throw new Error(`Invalid config ${filePath}:\n${msgs}`);
738
+ }
739
+ // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
740
+ if (!isJsOrTs(filePath) &&
741
+ (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
742
+ throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
743
+ `Use JS/TS config for "dynamic" or "schema".`);
744
+ }
745
+ return getDotenvConfigSchemaResolved.parse(parsed.data);
746
+ };
747
+ /**
748
+ * Discover and load configs into resolved shapes, ordered by scope/privacy.
749
+ * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
750
+ */
751
+ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
752
+ const discovered = await discoverConfigFiles(importMetaUrl);
753
+ const result = {};
754
+ for (const f of discovered) {
755
+ const cfg = await loadConfigFile(f.path);
756
+ if (f.scope === 'packaged') {
757
+ // packaged public only
758
+ result.packaged = cfg;
759
+ }
760
+ else {
761
+ result.project ??= {};
762
+ if (f.privacy === 'public')
763
+ result.project.public = cfg;
764
+ else
765
+ result.project.local = cfg;
766
+ }
767
+ }
768
+ return result;
769
+ };
770
+
771
+ /**
772
+ * Dotenv expansion utilities.
773
+ *
774
+ * This module implements recursive expansion of environment-variable
775
+ * references in strings and records. It supports both whitespace and
776
+ * bracket syntaxes with optional defaults:
777
+ *
778
+ * - Whitespace: `$VAR[:default]`
779
+ * - Bracketed: `${VAR[:default]}`
780
+ *
781
+ * Escaped dollar signs (`\$`) are preserved.
782
+ * Unknown variables resolve to empty string unless a default is provided.
783
+ */
784
+ /**
785
+ * Like String.prototype.search but returns the last index.
786
+ * @internal
787
+ */
788
+ const searchLast = (str, rgx) => {
789
+ const matches = Array.from(str.matchAll(rgx));
790
+ return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
791
+ };
792
+ const replaceMatch = (value, match, ref) => {
793
+ /**
794
+ * @internal
795
+ */
796
+ const group = match[0];
797
+ const key = match[1];
798
+ const defaultValue = match[2];
799
+ if (!key)
800
+ return value;
801
+ const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
802
+ return interpolate(replacement, ref);
803
+ };
804
+ const interpolate = (value = '', ref = {}) => {
805
+ /**
806
+ * @internal
807
+ */
808
+ // if value is falsy, return it as is
809
+ if (!value)
810
+ return value;
811
+ // get position of last unescaped dollar sign
812
+ const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
813
+ // return value if none found
814
+ if (lastUnescapedDollarSignIndex === -1)
815
+ return value;
816
+ // evaluate the value tail
817
+ const tail = value.slice(lastUnescapedDollarSignIndex);
818
+ // find whitespace pattern: $KEY:DEFAULT
819
+ const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
820
+ const whitespaceMatch = whitespacePattern.exec(tail);
821
+ if (whitespaceMatch != null)
822
+ return replaceMatch(value, whitespaceMatch, ref);
823
+ else {
824
+ // find bracket pattern: ${KEY:DEFAULT}
825
+ const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
826
+ const bracketMatch = bracketPattern.exec(tail);
827
+ if (bracketMatch != null)
828
+ return replaceMatch(value, bracketMatch, ref);
829
+ }
830
+ return value;
831
+ };
832
+ /**
833
+ * Recursively expands environment variables in a string. Variables may be
834
+ * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
835
+ * Unknown variables will expand to an empty string.
836
+ *
837
+ * @param value - The string to expand.
838
+ * @param ref - The reference object to use for variable expansion.
839
+ * @returns The expanded string.
840
+ *
841
+ * @example
842
+ * ```ts
843
+ * process.env.FOO = 'bar';
844
+ * dotenvExpand('Hello $FOO'); // "Hello bar"
845
+ * dotenvExpand('Hello $BAZ:world'); // "Hello world"
846
+ * ```
847
+ *
848
+ * @remarks
849
+ * The expansion is recursive. If a referenced variable itself contains
850
+ * references, those will also be expanded until a stable value is reached.
851
+ * Escaped references (e.g. `\$FOO`) are preserved as literals.
852
+ */
853
+ const dotenvExpand = (value, ref = process.env) => {
854
+ const result = interpolate(value, ref);
855
+ return result ? result.replace(/\\\$/g, '$') : undefined;
856
+ };
857
+ /**
858
+ * Recursively expands environment variables in the values of a JSON object.
859
+ * Variables may be presented with optional default as `$VAR[:default]` or
860
+ * `${VAR[:default]}`. Unknown variables will expand to an empty string.
861
+ *
862
+ * @param values - The values object to expand.
863
+ * @param options - Expansion options.
864
+ * @returns The value object with expanded string values.
865
+ *
866
+ * @example
867
+ * ```ts
868
+ * process.env.FOO = 'bar';
869
+ * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
870
+ * // => { A: "bar", B: "xbary" }
871
+ * ```
872
+ *
873
+ * @remarks
874
+ * Options:
875
+ * - ref: The reference object to use for expansion (defaults to process.env).
876
+ * - progressive: Whether to progressively add expanded values to the set of
877
+ * reference keys.
878
+ *
879
+ * When `progressive` is true, each expanded key becomes available for
880
+ * subsequent expansions in the same object (left-to-right by object key order).
881
+ */
882
+ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
883
+ const { ref = process.env, progressive = false } = options;
884
+ acc[key] = dotenvExpand(values[key], {
885
+ ...ref,
886
+ ...(progressive ? acc : {}),
887
+ });
888
+ return acc;
889
+ }, {});
890
+ /**
891
+ * Recursively expands environment variables in a string using `process.env` as
892
+ * the expansion reference. Variables may be presented with optional default as
893
+ * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
894
+ * empty string.
895
+ *
896
+ * @param value - The string to expand.
897
+ * @returns The expanded string.
898
+ *
899
+ * @example
900
+ * ```ts
901
+ * process.env.FOO = 'bar';
902
+ * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
903
+ * ```
904
+ */
905
+ const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
906
+
907
+ const applyKv = (current, kv) => {
908
+ if (!kv || Object.keys(kv).length === 0)
909
+ return current;
910
+ const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
911
+ return { ...current, ...expanded };
912
+ };
913
+ const applyConfigSlice = (current, cfg, env) => {
914
+ if (!cfg)
915
+ return current;
916
+ // kind axis: global then env (env overrides global)
917
+ const afterGlobal = applyKv(current, cfg.vars);
918
+ const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
919
+ return applyKv(afterGlobal, envKv);
920
+ };
921
+ /**
922
+ * Overlay config-provided values onto a base ProcessEnv using precedence axes:
923
+ * - kind: env \> global
924
+ * - privacy: local \> public
925
+ * - source: project \> packaged \> base
926
+ *
927
+ * Programmatic explicit vars (if provided) override all config slices.
928
+ * Progressive expansion is applied within each slice.
929
+ */
930
+ const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
931
+ let current = { ...base };
932
+ // Source: packaged (public -> local)
933
+ current = applyConfigSlice(current, configs.packaged, env);
934
+ // Packaged "local" is not expected by policy; if present, honor it.
935
+ // We do not have a separate object for packaged.local in sources, keep as-is.
936
+ // Source: project (public -> local)
937
+ current = applyConfigSlice(current, configs.project?.public, env);
938
+ current = applyConfigSlice(current, configs.project?.local, env);
939
+ // Programmatic explicit vars (top of static tier)
940
+ if (programmaticVars) {
941
+ const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
942
+ current = applyKv(current, toApply);
943
+ }
944
+ return current;
945
+ };
946
+
947
+ /**
948
+ * Asynchronously read a dotenv file & parse it into an object.
949
+ *
950
+ * @param path - Path to dotenv file.
951
+ * @returns The parsed dotenv object.
952
+ */
953
+ const readDotenv = async (path) => {
954
+ try {
955
+ return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
956
+ }
957
+ catch {
958
+ return {};
959
+ }
960
+ };
961
+
962
+ const importDefault = async (fileUrl) => {
963
+ const mod = (await import(fileUrl));
964
+ return mod.default;
965
+ };
966
+ const cacheHash = (absPath, mtimeMs) => createHash('sha1')
967
+ .update(absPath)
968
+ .update(String(mtimeMs))
969
+ .digest('hex')
970
+ .slice(0, 12);
971
+ /**
972
+ * Remove older compiled cache files for a given source base name, keeping
973
+ * at most `keep` most-recent files. Errors are ignored by design.
974
+ */
975
+ const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
976
+ try {
977
+ const entries = await fs.readdir(cacheDir);
978
+ const mine = entries
979
+ .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
980
+ .map((f) => path.join(cacheDir, f));
981
+ if (mine.length <= keep)
982
+ return;
983
+ const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
984
+ stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
985
+ const toDelete = stats.slice(keep).map((s) => s.p);
986
+ await Promise.all(toDelete.map(async (p) => {
987
+ try {
988
+ await fs.remove(p);
989
+ }
990
+ catch {
991
+ // best-effort cleanup
992
+ }
993
+ }));
994
+ }
995
+ catch {
996
+ // best-effort cleanup
997
+ }
998
+ };
999
+ /**
1000
+ * Load a module default export from a JS/TS file with robust fallbacks:
1001
+ * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1002
+ * 1) try direct import (if a TS loader is active),
1003
+ * 2) esbuild bundle to a temp ESM file,
1004
+ * 3) typescript.transpileModule fallback for simple modules.
1005
+ *
1006
+ * @param absPath - absolute path to source file
1007
+ * @param cacheDirName - cache subfolder under .tsbuild
1008
+ */
1009
+ const loadModuleDefault = async (absPath, cacheDirName) => {
1010
+ const ext = path.extname(absPath).toLowerCase();
1011
+ const fileUrl = url.pathToFileURL(absPath).toString();
1012
+ if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1013
+ return importDefault(fileUrl);
1014
+ }
1015
+ // Try direct import first (TS loader active)
1016
+ try {
1017
+ const dyn = await importDefault(fileUrl);
1018
+ if (dyn)
1019
+ return dyn;
1020
+ }
1021
+ catch {
1022
+ /* fall through */
1023
+ }
1024
+ const stat = await fs.stat(absPath);
1025
+ const hash = cacheHash(absPath, stat.mtimeMs);
1026
+ const cacheDir = path.resolve('.tsbuild', cacheDirName);
1027
+ await fs.ensureDir(cacheDir);
1028
+ const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
1029
+ // Try esbuild
1030
+ try {
1031
+ const esbuild = (await import('esbuild'));
1032
+ await esbuild.build({
1033
+ entryPoints: [absPath],
1034
+ bundle: true,
1035
+ platform: 'node',
1036
+ format: 'esm',
1037
+ target: 'node20',
1038
+ outfile: cacheFile,
1039
+ sourcemap: false,
1040
+ logLevel: 'silent',
1041
+ });
1042
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1043
+ // Best-effort: trim older cache files for this source.
1044
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1045
+ return result;
1046
+ }
1047
+ catch {
1048
+ /* fall through to TS transpile */
1049
+ }
1050
+ // TypeScript transpile fallback
1051
+ try {
1052
+ const ts = (await import('typescript'));
1053
+ const code = await fs.readFile(absPath, 'utf-8');
1054
+ const out = ts.transpileModule(code, {
1055
+ compilerOptions: {
1056
+ module: 'ESNext',
1057
+ target: 'ES2022',
1058
+ moduleResolution: 'NodeNext',
1059
+ },
1060
+ }).outputText;
1061
+ await fs.writeFile(cacheFile, out, 'utf-8');
1062
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1063
+ // Best-effort: trim older cache files for this source.
1064
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1065
+ return result;
1066
+ }
1067
+ catch {
1068
+ // Caller decides final error wording; rethrow for upstream mapping.
1069
+ throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
1070
+ }
1071
+ };
1072
+
1073
+ /**
1074
+ * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
1075
+ *
1076
+ * @param options - `GetDotenvOptions` object
1077
+ * @returns The combined parsed dotenv object.
1078
+ * * @example Load from the project root with default tokens
1079
+ * ```ts
1080
+ * const vars = await getDotenv();
1081
+ * console.log(vars.MY_SETTING);
1082
+ * ```
1083
+ *
1084
+ * @example Load from multiple paths and a specific environment
1085
+ * ```ts
1086
+ * const vars = await getDotenv({
1087
+ * env: 'dev',
1088
+ * dotenvToken: '.testenv',
1089
+ * privateToken: 'secret',
1090
+ * paths: ['./', './packages/app'],
1091
+ * });
1092
+ * ```
1093
+ *
1094
+ * @example Use dynamic variables
1095
+ * ```ts
1096
+ * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
1097
+ * const vars = await getDotenv({ dynamicPath: '.env.js' });
1098
+ * ```
1099
+ *
1100
+ * @remarks
1101
+ * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
1102
+ * into `process.env` as a side effect.
1103
+ * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
1104
+ * The path is resolved after expansion, so it may reference previously loaded vars.
1105
+ *
1106
+ * @throws Error when a dynamic module is present but cannot be imported.
1107
+ * @throws Error when an output path was requested but could not be resolved.
1108
+ */
1109
+ const getDotenv = async (options = {}) => {
1110
+ // Apply defaults.
1111
+ 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);
1112
+ // Read .env files.
1113
+ const loaded = paths.length
1114
+ ? await paths.reduce(async (e, p) => {
1115
+ const publicGlobal = excludePublic || excludeGlobal
1116
+ ? Promise.resolve({})
1117
+ : readDotenv(path.resolve(p, dotenvToken));
1118
+ const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1119
+ ? Promise.resolve({})
1120
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1121
+ const privateGlobal = excludePrivate || excludeGlobal
1122
+ ? Promise.resolve({})
1123
+ : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1124
+ const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1125
+ ? Promise.resolve({})
1126
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1127
+ const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1128
+ e,
1129
+ publicGlobal,
1130
+ publicEnv,
1131
+ privateGlobal,
1132
+ privateEnv,
1133
+ ]);
1134
+ return {
1135
+ ...eResolved,
1136
+ ...publicGlobalResolved,
1137
+ ...publicEnvResolved,
1138
+ ...privateGlobalResolved,
1139
+ ...privateEnvResolved,
1140
+ };
1141
+ }, Promise.resolve({}))
1142
+ : {};
1143
+ const outputKey = nanoid();
1144
+ const dotenv = dotenvExpandAll({
1145
+ ...loaded,
1146
+ ...vars,
1147
+ ...(outputPath ? { [outputKey]: outputPath } : {}),
1148
+ }, { progressive: true });
1149
+ // Process dynamic variables. Programmatic option takes precedence over path.
1150
+ if (!excludeDynamic) {
1151
+ let dynamic = undefined;
1152
+ if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1153
+ dynamic = options.dynamic;
1154
+ }
1155
+ else if (dynamicPath) {
1156
+ const absDynamicPath = path.resolve(dynamicPath);
1157
+ if (await fs.exists(absDynamicPath)) {
1158
+ try {
1159
+ dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1160
+ }
1161
+ catch {
1162
+ // Preserve legacy error text for compatibility with tests/docs.
1163
+ throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1164
+ `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1165
+ }
1166
+ }
1167
+ }
1168
+ if (dynamic) {
1169
+ try {
1170
+ for (const key in dynamic)
1171
+ Object.assign(dotenv, {
1172
+ [key]: typeof dynamic[key] === 'function'
1173
+ ? dynamic[key](dotenv, env ?? defaultEnv)
1174
+ : dynamic[key],
1175
+ });
1176
+ }
1177
+ catch {
1178
+ throw new Error(`Unable to evaluate dynamic variables.`);
1179
+ }
1180
+ }
1181
+ }
1182
+ // Write output file.
1183
+ let resultDotenv = dotenv;
1184
+ if (outputPath) {
1185
+ const outputPathResolved = dotenv[outputKey];
1186
+ if (!outputPathResolved)
1187
+ throw new Error('Output path not found.');
1188
+ const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1189
+ await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
1190
+ const value = dotenvForOutput[key] ?? '';
1191
+ return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1192
+ }, ''), { encoding: 'utf-8' });
1193
+ resultDotenv = dotenvForOutput;
1194
+ }
1195
+ // Log result.
1196
+ if (log) {
1197
+ const redactFlag = options.redact ?? false;
1198
+ const redactPatterns = options.redactPatterns ?? undefined;
1199
+ const redOpts = {};
1200
+ if (redactFlag)
1201
+ redOpts.redact = true;
1202
+ if (redactFlag && Array.isArray(redactPatterns))
1203
+ redOpts.redactPatterns = redactPatterns;
1204
+ const bag = redactFlag
1205
+ ? redactObject(resultDotenv, redOpts)
1206
+ : { ...resultDotenv };
1207
+ logger.log(bag);
1208
+ // Entropy warnings: once-per-key-per-run (presentation only)
1209
+ const warnEntropyVal = options.warnEntropy ?? true;
1210
+ const entropyThresholdVal = options
1211
+ .entropyThreshold;
1212
+ const entropyMinLengthVal = options
1213
+ .entropyMinLength;
1214
+ const entropyWhitelistVal = options
1215
+ .entropyWhitelist;
1216
+ const entOpts = {};
1217
+ if (typeof warnEntropyVal === 'boolean')
1218
+ entOpts.warnEntropy = warnEntropyVal;
1219
+ if (typeof entropyThresholdVal === 'number')
1220
+ entOpts.entropyThreshold = entropyThresholdVal;
1221
+ if (typeof entropyMinLengthVal === 'number')
1222
+ entOpts.entropyMinLength = entropyMinLengthVal;
1223
+ if (Array.isArray(entropyWhitelistVal))
1224
+ entOpts.entropyWhitelist = entropyWhitelistVal;
1225
+ for (const [k, v] of Object.entries(resultDotenv)) {
1226
+ maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1227
+ logger.log(line);
1228
+ });
1229
+ }
1230
+ }
1231
+ // Load process.env.
1232
+ if (loadProcess)
1233
+ Object.assign(process.env, resultDotenv);
1234
+ return resultDotenv;
1235
+ };
1236
+
1237
+ /**
1238
+ * Deep interpolation utility for string leaves.
1239
+ * - Expands string values using dotenv-style expansion against the provided envRef.
1240
+ * - Preserves non-strings as-is.
1241
+ * - Does not recurse into arrays (arrays are returned unchanged).
1242
+ *
1243
+ * Intended for:
1244
+ * - Phase C option/config interpolation after composing ctx.dotenv.
1245
+ * - Per-plugin config slice interpolation before afterResolve.
1246
+ */
1247
+ /** @internal */
1248
+ const isPlainObject = (v) => v !== null &&
1249
+ typeof v === 'object' &&
1250
+ !Array.isArray(v) &&
1251
+ Object.getPrototypeOf(v) === Object.prototype;
1252
+ /**
1253
+ * Deeply interpolate string leaves against envRef.
1254
+ * Arrays are not recursed into; they are returned unchanged.
1255
+ *
1256
+ * @typeParam T - Shape of the input value.
1257
+ * @param value - Input value (object/array/primitive).
1258
+ * @param envRef - Reference environment for interpolation.
1259
+ * @returns A new value with string leaves interpolated.
1260
+ */
1261
+ const interpolateDeep = (value, envRef) => {
1262
+ // Strings: expand and return
1263
+ if (typeof value === 'string') {
1264
+ const out = dotenvExpand(value, envRef);
1265
+ // dotenvExpand returns string | undefined; preserve original on undefined
1266
+ return (out ?? value);
1267
+ }
1268
+ // Arrays: return as-is (no recursion)
1269
+ if (Array.isArray(value)) {
1270
+ return value;
1271
+ }
1272
+ // Plain objects: shallow clone and recurse into values
1273
+ if (isPlainObject(value)) {
1274
+ const src = value;
1275
+ const out = {};
1276
+ for (const [k, v] of Object.entries(src)) {
1277
+ // Recurse for strings/objects; keep arrays as-is; preserve other scalars
1278
+ if (typeof v === 'string')
1279
+ out[k] = dotenvExpand(v, envRef) ?? v;
1280
+ else if (Array.isArray(v))
1281
+ out[k] = v;
1282
+ else if (isPlainObject(v))
1283
+ out[k] = interpolateDeep(v, envRef);
1284
+ else
1285
+ out[k] = v;
1286
+ }
1287
+ return out;
1288
+ }
1289
+ // Other primitives/types: return as-is
1290
+ return value;
1291
+ };
1292
+
1293
+ /**
1294
+ * Compute the dotenv context for the host (uses the config loader/overlay path).
1295
+ * - Resolves and validates options strictly (host-only).
1296
+ * - Applies file cascade, overlays, dynamics, and optional effects.
1297
+ * - Merges and validates per-plugin config slices (when provided).
1298
+ *
1299
+ * @param customOptions - Partial options from the current invocation.
1300
+ * @param plugins - Installed plugins (for config validation).
1301
+ * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
1302
+ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1303
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
1304
+ const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1305
+ // Always-on loader path
1306
+ // 1) Base from files only (no dynamic, no programmatic vars)
1307
+ const base = await getDotenv({
1308
+ ...validated,
1309
+ // Build a pure base without side effects or logging.
1310
+ excludeDynamic: true,
1311
+ vars: {},
1312
+ log: false,
1313
+ loadProcess: false,
1314
+ outputPath: undefined,
1315
+ });
1316
+ // 2) Discover config sources and overlay
1317
+ const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1318
+ const dotenvOverlaid = overlayEnv({
1319
+ base,
1320
+ env: validated.env ?? validated.defaultEnv,
1321
+ configs: sources,
1322
+ ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1323
+ });
1324
+ // Helper to apply a dynamic map progressively.
1325
+ const applyDynamic = (target, dynamic, env) => {
1326
+ if (!dynamic)
1327
+ return;
1328
+ for (const key of Object.keys(dynamic)) {
1329
+ const value = typeof dynamic[key] === 'function'
1330
+ ? dynamic[key](target, env)
1331
+ : dynamic[key];
1332
+ Object.assign(target, { [key]: value });
1333
+ }
1334
+ };
1335
+ // 3) Apply dynamics in order
1336
+ const dotenv = { ...dotenvOverlaid };
1337
+ applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1338
+ applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1339
+ applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1340
+ applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1341
+ // file dynamicPath (lowest)
1342
+ if (validated.dynamicPath) {
1343
+ const absDynamicPath = path.resolve(validated.dynamicPath);
1344
+ try {
1345
+ const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
1346
+ applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
1347
+ }
1348
+ catch {
1349
+ throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
1350
+ }
1351
+ }
1352
+ // 4) Output/log/process merge
1353
+ if (validated.outputPath) {
1354
+ await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
1355
+ const value = dotenv[key] ?? '';
1356
+ return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1357
+ }, ''), { encoding: 'utf-8' });
1358
+ }
1359
+ const logger = validated.logger ?? console;
1360
+ if (validated.log)
1361
+ logger.log(dotenv);
1362
+ if (validated.loadProcess)
1363
+ Object.assign(process.env, dotenv);
1364
+ // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
1365
+ const packagedPlugins = (sources.packaged &&
1366
+ sources.packaged.plugins) ??
1367
+ {};
1368
+ const publicPlugins = (sources.project?.public &&
1369
+ sources.project.public.plugins) ??
1370
+ {};
1371
+ const localPlugins = (sources.project?.local &&
1372
+ sources.project.local.plugins) ??
1373
+ {};
1374
+ const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
1375
+ for (const p of plugins) {
1376
+ if (!p.id)
1377
+ continue;
1378
+ const slice = mergedPluginConfigs[p.id];
1379
+ if (slice === undefined)
1380
+ continue;
1381
+ // Per-plugin interpolation just before validation/afterResolve:
1382
+ // precedence: process.env wins over ctx.dotenv for slice defaults.
1383
+ const envRef = {
1384
+ ...dotenv,
1385
+ ...process.env,
1386
+ };
1387
+ const interpolated = interpolateDeep(slice, envRef);
1388
+ // Validate if a schema is provided; otherwise accept interpolated slice as-is.
1389
+ if (p.configSchema) {
1390
+ const parsed = p.configSchema.safeParse(interpolated);
1391
+ if (!parsed.success) {
1392
+ const msgs = parsed.error.issues
1393
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
1394
+ .join('\n');
1395
+ throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
1396
+ }
1397
+ mergedPluginConfigs[p.id] = parsed.data;
1398
+ }
1399
+ else {
1400
+ mergedPluginConfigs[p.id] = interpolated;
1401
+ }
1402
+ }
1403
+ return {
1404
+ optionsResolved: validated,
1405
+ dotenv: dotenv,
1406
+ plugins: {},
1407
+ pluginConfigs: mergedPluginConfigs,
1408
+ };
1409
+ };
1410
+
1411
+ const HOST_META_URL = import.meta.url;
1412
+ const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
1413
+ const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
1414
+ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1415
+ /**
1416
+ * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
1417
+ *
1418
+ * Responsibilities:
1419
+ * - Resolve options strictly and compute dotenv context (resolveAndLoad).
1420
+ * - Expose a stable accessor for the current context (getCtx).
1421
+ * - Provide a namespacing helper (ns).
1422
+ * - Support composable plugins with parent → children install and afterResolve.
1423
+ *
1424
+ * NOTE: This host is additive and does not alter the legacy CLI.
1425
+ */
1426
+ class GetDotenvCli extends Command {
1427
+ /** Registered top-level plugins (composition happens via .use()) */
1428
+ _plugins = [];
1429
+ /** One-time installation guard */
1430
+ _installed = false;
1431
+ /** Optional header line to prepend in help output */
1432
+ [HELP_HEADER_SYMBOL];
1433
+ constructor(alias = 'getdotenv') {
1434
+ super(alias);
1435
+ // Ensure subcommands that use passThroughOptions can be attached safely.
1436
+ // Commander requires parent commands to enable positional options when a
1437
+ // child uses passThroughOptions.
1438
+ this.enablePositionalOptions();
1439
+ // Configure grouped help: show only base options in default "Options";
1440
+ // append App/Plugin sections after default help.
1441
+ this.configureHelp({
1442
+ visibleOptions: (cmd) => {
1443
+ const all = cmd.options ??
1444
+ [];
1445
+ const base = all.filter((opt) => {
1446
+ const group = opt.__group;
1447
+ return group === 'base';
1448
+ });
1449
+ // Sort: short-aliased options first, then long-only; stable by flags.
1450
+ const hasShort = (opt) => {
1451
+ const flags = opt.flags ?? '';
1452
+ // Matches "-x," or starting "-x " before any long
1453
+ return /(^|\s|,)-[A-Za-z]/.test(flags);
1454
+ };
1455
+ const byFlags = (opt) => opt.flags ?? '';
1456
+ base.sort((a, b) => {
1457
+ const aS = hasShort(a) ? 1 : 0;
1458
+ const bS = hasShort(b) ? 1 : 0;
1459
+ return bS - aS || byFlags(a).localeCompare(byFlags(b));
1460
+ });
1461
+ return base;
1462
+ },
1463
+ });
1464
+ this.addHelpText('beforeAll', () => {
1465
+ const header = this[HELP_HEADER_SYMBOL];
1466
+ return header && header.length > 0 ? `${header}\n\n` : '';
1467
+ });
1468
+ this.addHelpText('afterAll', (ctx) => this.#renderOptionGroups(ctx.command));
1469
+ // Skeleton preSubcommand hook: produce a context if absent, without
1470
+ // mutating process.env. The passOptions hook (when installed) will // compute the final context using merged CLI options; keeping
1471
+ // loadProcess=false here avoids leaking dotenv values into the parent
1472
+ // process env before subcommands execute.
1473
+ this.hook('preSubcommand', async () => {
1474
+ if (this.getCtx())
1475
+ return;
1476
+ await this.resolveAndLoad({ loadProcess: false });
1477
+ });
1478
+ }
1479
+ /**
1480
+ * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
1481
+ */
1482
+ async resolveAndLoad(customOptions = {}) {
1483
+ // Resolve defaults, then validate strictly under the new host.
1484
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
1485
+ getDotenvOptionsSchemaResolved.parse(optionsResolved);
1486
+ // Delegate the heavy lifting to the shared helper (guarded path supported).
1487
+ const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
1488
+ // Persist context on the instance for later access.
1489
+ this[CTX_SYMBOL] =
1490
+ ctx;
1491
+ // Ensure plugins are installed exactly once, then run afterResolve.
1492
+ await this.install();
1493
+ await this._runAfterResolve(ctx);
1494
+ return ctx;
1495
+ }
1496
+ /**
1497
+ * Retrieve the current invocation context (if any).
1498
+ */
1499
+ getCtx() {
1500
+ return this[CTX_SYMBOL];
1501
+ }
1502
+ /**
1503
+ * Retrieve the merged root CLI options bag (if set by passOptions()).
1504
+ * Downstream-safe: no generics required.
1505
+ */
1506
+ getOptions() {
1507
+ return this[OPTS_SYMBOL];
1508
+ }
1509
+ /** Internal: set the merged root options bag for this run. */
1510
+ _setOptionsBag(bag) {
1511
+ this[OPTS_SYMBOL] = bag;
1512
+ }
1513
+ /** * Convenience helper to create a namespaced subcommand.
1514
+ */
1515
+ ns(name) {
1516
+ return this.command(name);
1517
+ }
1518
+ /**
1519
+ * Tag options added during the provided callback as 'app' for grouped help.
1520
+ * Allows downstream apps to demarcate their root-level options.
1521
+ */
1522
+ tagAppOptions(fn) {
1523
+ const root = this;
1524
+ const originalAddOption = root.addOption.bind(root);
1525
+ const originalOption = root.option.bind(root);
1526
+ const tagLatest = (cmd, group) => {
1527
+ const optsArr = cmd.options;
1528
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
1529
+ const last = optsArr[optsArr.length - 1];
1530
+ last.__group = group;
1531
+ }
1532
+ };
1533
+ root.addOption = function patchedAdd(opt) {
1534
+ opt.__group = 'app';
1535
+ return originalAddOption(opt);
1536
+ };
1537
+ root.option = function patchedOption(...args) {
1538
+ const ret = originalOption(...args);
1539
+ tagLatest(this, 'app');
1540
+ return ret;
1541
+ };
1542
+ try {
1543
+ return fn(root);
1544
+ }
1545
+ finally {
1546
+ root.addOption = originalAddOption;
1547
+ root.option = originalOption;
1548
+ }
1549
+ }
1550
+ /**
1551
+ * Branding helper: set CLI name/description/version and optional help header.
1552
+ * If version is omitted and importMetaUrl is provided, attempts to read the
1553
+ * nearest package.json version (best-effort; non-fatal on failure).
1554
+ */
1555
+ async brand(args) {
1556
+ const { name, description, version, importMetaUrl, helpHeader } = args;
1557
+ if (typeof name === 'string' && name.length > 0)
1558
+ this.name(name);
1559
+ if (typeof description === 'string')
1560
+ this.description(description);
1561
+ let v = version;
1562
+ if (!v && importMetaUrl) {
1563
+ try {
1564
+ const fromUrl = fileURLToPath(importMetaUrl);
1565
+ const pkgDir = await packageDirectory({ cwd: fromUrl });
1566
+ if (pkgDir) {
1567
+ const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1568
+ const pkg = JSON.parse(txt);
1569
+ if (pkg.version)
1570
+ v = pkg.version;
1571
+ }
1572
+ }
1573
+ catch {
1574
+ // best-effort only
1575
+ }
1576
+ }
1577
+ if (v)
1578
+ this.version(v);
1579
+ // Help header:
1580
+ // - If caller provides helpHeader, use it.
1581
+ // - Otherwise, when a version is known, default to "<name> v<version>".
1582
+ if (typeof helpHeader === 'string') {
1583
+ this[HELP_HEADER_SYMBOL] = helpHeader;
1584
+ }
1585
+ else if (v) {
1586
+ // Use the current command name (possibly overridden by 'name' above).
1587
+ const header = `${this.name()} v${v}`;
1588
+ this[HELP_HEADER_SYMBOL] = header;
1589
+ }
1590
+ return this;
1591
+ }
1592
+ /**
1593
+ * Register a plugin for installation (parent level).
1594
+ * Installation occurs on first resolveAndLoad() (or explicit install()).
1595
+ */
1596
+ use(plugin) {
1597
+ this._plugins.push(plugin);
1598
+ // Immediately run setup so subcommands exist before parsing.
1599
+ const setupOne = (p) => {
1600
+ p.setup(this);
1601
+ for (const child of p.children)
1602
+ setupOne(child);
1603
+ };
1604
+ setupOne(plugin);
1605
+ return this;
1606
+ }
1607
+ /**
1608
+ * Install all registered plugins in parent → children (pre-order).
1609
+ * Runs only once per CLI instance.
1610
+ */
1611
+ async install() {
1612
+ // Setup is performed immediately in use(); here we only guard for afterResolve.
1613
+ this._installed = true;
1614
+ // Satisfy require-await without altering behavior.
1615
+ await Promise.resolve();
1616
+ }
1617
+ /**
1618
+ * Run afterResolve hooks for all plugins (parent → children).
1619
+ */
1620
+ async _runAfterResolve(ctx) {
1621
+ const run = async (p) => {
1622
+ if (p.afterResolve)
1623
+ await p.afterResolve(this, ctx);
1624
+ for (const child of p.children)
1625
+ await run(child);
1626
+ };
1627
+ for (const p of this._plugins)
1628
+ await run(p);
1629
+ }
1630
+ // Render App/Plugin grouped options appended after default help.
1631
+ #renderOptionGroups(cmd) {
1632
+ const all = cmd.options ?? [];
1633
+ const byGroup = new Map();
1634
+ for (const o of all) {
1635
+ const opt = o;
1636
+ const g = opt.__group;
1637
+ if (!g || g === 'base')
1638
+ continue; // base handled by default help
1639
+ const rows = byGroup.get(g) ?? [];
1640
+ rows.push({
1641
+ flags: opt.flags ?? '',
1642
+ description: opt.description ?? '',
1643
+ });
1644
+ byGroup.set(g, rows);
1645
+ }
1646
+ if (byGroup.size === 0)
1647
+ return '';
1648
+ const renderRows = (title, rows) => {
1649
+ const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1650
+ // Sort within group: short-aliased flags first
1651
+ rows.sort((a, b) => {
1652
+ const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1653
+ const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1654
+ return bS - aS || a.flags.localeCompare(b.flags);
1655
+ });
1656
+ const lines = rows
1657
+ .map((r) => {
1658
+ const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1659
+ return ` ${r.flags}${pad}${r.description}`.trimEnd();
1660
+ })
1661
+ .join('\n');
1662
+ return `\n${title}:\n${lines}\n`;
1663
+ };
1664
+ let out = '';
1665
+ // App options (if any)
1666
+ const app = byGroup.get('app');
1667
+ if (app && app.length > 0) {
1668
+ out += renderRows('App options', app);
1669
+ }
1670
+ // Plugin groups sorted by id
1671
+ const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1672
+ pluginKeys.sort((a, b) => a.localeCompare(b));
1673
+ for (const k of pluginKeys) {
1674
+ const id = k.slice('plugin:'.length) || '(unknown)';
1675
+ const rows = byGroup.get(k) ?? [];
1676
+ if (rows.length > 0) {
1677
+ out += renderRows(`Plugin options — ${id}`, rows);
1678
+ }
1679
+ }
1680
+ return out;
1681
+ }
1682
+ }
1683
+
1684
+ /**
1685
+ * Validate a composed env against config-provided validation surfaces.
1686
+ * Precedence for validation definitions:
1687
+ * project.local -\> project.public -\> packaged
1688
+ *
1689
+ * Behavior:
1690
+ * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
1691
+ * - Else if `requiredKeys` is present, check presence (value !== undefined).
1692
+ * - Returns a flat list of issue strings; caller decides warn vs fail.
1693
+ */
1694
+ const validateEnvAgainstSources = (finalEnv, sources) => {
1695
+ const pick = (getter) => {
1696
+ const pl = sources.project?.local;
1697
+ const pp = sources.project?.public;
1698
+ const pk = sources.packaged;
1699
+ return ((pl && getter(pl)) ||
1700
+ (pp && getter(pp)) ||
1701
+ (pk && getter(pk)) ||
1702
+ undefined);
1703
+ };
1704
+ const schema = pick((cfg) => cfg['schema']);
1705
+ if (schema &&
1706
+ typeof schema.safeParse === 'function') {
1707
+ try {
1708
+ const parsed = schema.safeParse(finalEnv);
1709
+ if (!parsed.success) {
1710
+ // Try to render zod-style issues when available.
1711
+ const err = parsed.error;
1712
+ const issues = Array.isArray(err.issues) && err.issues.length > 0
1713
+ ? err.issues.map((i) => {
1714
+ const path = Array.isArray(i.path) ? i.path.join('.') : '';
1715
+ const msg = i.message ?? 'Invalid value';
1716
+ return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
1717
+ })
1718
+ : ['[schema] validation failed'];
1719
+ return issues;
1720
+ }
1721
+ return [];
1722
+ }
1723
+ catch {
1724
+ // If schema invocation fails, surface a single diagnostic.
1725
+ return [
1726
+ '[schema] validation failed (unable to execute schema.safeParse)',
1727
+ ];
1728
+ }
1729
+ }
1730
+ const requiredKeys = pick((cfg) => cfg['requiredKeys']);
1731
+ if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
1732
+ const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
1733
+ if (missing.length > 0) {
1734
+ return missing.map((k) => `[requiredKeys] missing: ${k}`);
1735
+ }
1736
+ }
1737
+ return [];
1738
+ };
1739
+
1740
+ /**
1741
+ * Attach legacy root flags to a Commander program.
1742
+ * Uses provided defaults to render help labels without coupling to generators.
1743
+ */
1744
+ const attachRootOptions = (program, defaults, opts) => {
1745
+ // Install temporary wrappers to tag all options added here as "base".
1746
+ const GROUP = 'base';
1747
+ const tagLatest = (cmd, group) => {
1748
+ const optsArr = cmd.options;
1749
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
1750
+ const last = optsArr[optsArr.length - 1];
1751
+ last.__group = group;
1752
+ }
1753
+ };
1754
+ const originalAddOption = program.addOption.bind(program);
1755
+ const originalOption = program.option.bind(program);
1756
+ program.addOption = function patchedAdd(opt) {
1757
+ // Tag before adding, in case consumers inspect the Option directly.
1758
+ opt.__group = GROUP;
1759
+ const ret = originalAddOption(opt);
1760
+ return ret;
1761
+ };
1762
+ program.option = function patchedOption(...args) {
1763
+ const ret = originalOption(...args);
1764
+ tagLatest(this, GROUP);
1765
+ return ret;
1766
+ };
1767
+ const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1768
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1769
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1770
+ // Build initial chain.
1771
+ let p = program
1772
+ .enablePositionalOptions()
1773
+ .passThroughOptions()
1774
+ .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1775
+ p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1776
+ ['KEY1', 'VAL1'],
1777
+ ['KEY2', 'VAL2'],
1778
+ ]
1779
+ .map((v) => v.join(va))
1780
+ .join(vd)}`, dotenvExpandFromProcessEnv);
1781
+ // Optional legacy root command flag (kept for generated CLI compatibility).
1782
+ // Default is OFF; the generator opts in explicitly.
1783
+ if (opts?.includeCommandOption === true) {
1784
+ p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1785
+ }
1786
+ p = p
1787
+ .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
1788
+ .addOption(new Option('-s, --shell [string]', (() => {
1789
+ let defaultLabel = '';
1790
+ if (shell !== undefined) {
1791
+ if (typeof shell === 'boolean') {
1792
+ defaultLabel = ' (default OS shell)';
1793
+ }
1794
+ else if (typeof shell === 'string') {
1795
+ // Safe string interpolation
1796
+ defaultLabel = ` (default ${shell})`;
1797
+ }
1798
+ }
1799
+ return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
1800
+ })()).conflicts('shellOff'))
1801
+ .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
1802
+ .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
1803
+ .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
1804
+ .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1805
+ ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1806
+ ? ' (default)'
1807
+ : ''}`).conflicts('excludeAllOff'))
1808
+ .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
1809
+ .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
1810
+ .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
1811
+ .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
1812
+ .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
1813
+ .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
1814
+ .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
1815
+ .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
1816
+ .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
1817
+ .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
1818
+ .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
1819
+ .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
1820
+ .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
1821
+ .option('--capture', 'capture child process stdio for commands (tests/CI)')
1822
+ .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
1823
+ .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
1824
+ .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
1825
+ .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
1826
+ .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
1827
+ .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
1828
+ .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
1829
+ .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
1830
+ .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
1831
+ .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
1832
+ .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
1833
+ .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1834
+ // Hidden scripts pipe-through (stringified)
1835
+ .addOption(new Option('--scripts <string>')
1836
+ .default(JSON.stringify(scripts))
1837
+ .hideHelp());
1838
+ // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1839
+ p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1840
+ // Validation: strict mode fails on env validation issues (warn by default).
1841
+ p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1842
+ // Entropy diagnostics (presentation-only)
1843
+ p = p
1844
+ .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
1845
+ .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
1846
+ .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
1847
+ .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
1848
+ .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
1849
+ .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1850
+ // Restore original methods to avoid tagging future additions outside base.
1851
+ program.addOption = originalAddOption;
1852
+ program.option = originalOption;
1853
+ return p;
1854
+ };
1855
+
1856
+ /**
1857
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1858
+ * - If the user explicitly enabled the flag, return true.
1859
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1860
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
1861
+ *
1862
+ * @param exclude - The "on" flag value as parsed by Commander.
1863
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1864
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1865
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1866
+ *
1867
+ * @example
1868
+ * ```ts
1869
+ * resolveExclusion(undefined, undefined, true); // => true
1870
+ * ```
1871
+ */
1872
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1873
+ /**
1874
+ * Resolve an optional flag with "--exclude-all" overrides.
1875
+ * If excludeAll is set and the individual "...-off" is not, force true.
1876
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1877
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
1878
+ *
1879
+ * @param exclude - Individual include/exclude flag.
1880
+ * @param excludeOff - Individual "...-off" flag.
1881
+ * @param defaultValue - Default for the individual flag.
1882
+ * @param excludeAll - Global "exclude-all" flag.
1883
+ * @param excludeAllOff - Global "exclude-all-off" flag.
1884
+ *
1885
+ * @example
1886
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1887
+ */
1888
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1889
+ // Order of precedence:
1890
+ // 1) Individual explicit "on" wins outright.
1891
+ // 2) Individual explicit "off" wins over any global.
1892
+ // 3) Global exclude-all forces true when not explicitly turned off.
1893
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1894
+ // 5) Fall back to the default (true => set; false/undefined => unset).
1895
+ (() => {
1896
+ // Individual "on"
1897
+ if (exclude === true)
1898
+ return true;
1899
+ // Individual "off"
1900
+ if (excludeOff === true)
1901
+ return undefined;
1902
+ // Global "exclude-all" ON (unless explicitly turned off)
1903
+ if (excludeAll === true)
1904
+ return true;
1905
+ // Global "exclude-all-off" (unless explicitly enabled)
1906
+ if (excludeAllOff === true)
1907
+ return undefined;
1908
+ // Default
1909
+ return defaultValue ? true : undefined;
1910
+ })();
1911
+ /**
1912
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1913
+ * delete when undefined; assign when defined — without requiring an index signature on T.
1914
+ *
1915
+ * @typeParam T - Target object type.
1916
+ * @param obj - The object to write to.
1917
+ * @param key - The optional boolean property key of {@link T}.
1918
+ * @param value - The value to set or `undefined` to unset.
1919
+ *
1920
+ * @remarks
1921
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1922
+ */
1923
+ const setOptionalFlag = (obj, key, value) => {
1924
+ const target = obj;
1925
+ const k = key;
1926
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1927
+ if (value === undefined)
1928
+ delete target[k];
1929
+ else
1930
+ target[k] = value;
1931
+ };
1932
+
1933
+ /**
1934
+ * Merge and normalize raw Commander options (current + parent + defaults)
1935
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1936
+ * avoid cross-layer coupling; callers may cast as needed.
1937
+ */
1938
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1939
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
1940
+ ? JSON.parse(parentJson)
1941
+ : undefined;
1942
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1943
+ const current = { ...rest };
1944
+ if (typeof scripts === 'string') {
1945
+ try {
1946
+ current.scripts = JSON.parse(scripts);
1947
+ }
1948
+ catch {
1949
+ // ignore parse errors; leave scripts undefined
1950
+ }
1951
+ }
1952
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1953
+ const d = defaults;
1954
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1955
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1956
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1957
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1958
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1959
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1960
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1961
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1962
+ // warnEntropy (tri-state)
1963
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1964
+ // Normalize shell for predictability: explicit default shell per OS.
1965
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1966
+ let resolvedShell = merged.shell;
1967
+ if (shellOff)
1968
+ resolvedShell = false;
1969
+ else if (resolvedShell === true || resolvedShell === undefined) {
1970
+ resolvedShell = defaultShell;
1971
+ }
1972
+ else if (typeof resolvedShell !== 'string' &&
1973
+ typeof defaults.shell === 'string') {
1974
+ resolvedShell = defaults.shell;
1975
+ }
1976
+ merged.shell = resolvedShell;
1977
+ const cmd = typeof command === 'string' ? command : undefined;
1978
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
1979
+ };
1980
+
1981
+ GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1982
+ const d = (defaults ?? baseRootOptionDefaults);
1983
+ attachRootOptions(this, d, opts);
1984
+ return this;
1985
+ };
1986
+ GetDotenvCli.prototype.passOptions = function (defaults) {
1987
+ const d = (defaults ?? baseRootOptionDefaults);
1988
+ this.hook('preSubcommand', async (thisCommand) => {
1989
+ const raw = thisCommand.opts();
1990
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1991
+ // Persist merged options for nested invocations (batch exec).
1992
+ thisCommand.getDotenvCliOptions =
1993
+ merged;
1994
+ // Also store on the host for downstream ergonomic accessors.
1995
+ this._setOptionsBag(merged);
1996
+ // Build service options and compute context (always-on config loader path).
1997
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1998
+ await this.resolveAndLoad(serviceOptions);
1999
+ // Global validation: once after Phase C using config sources.
2000
+ try {
2001
+ const ctx = this.getCtx();
2002
+ const dotenv = (ctx?.dotenv ?? {});
2003
+ const sources = await resolveGetDotenvConfigSources(import.meta.url);
2004
+ const issues = validateEnvAgainstSources(dotenv, sources);
2005
+ if (Array.isArray(issues) && issues.length > 0) {
2006
+ const logger = (merged.logger ??
2007
+ console);
2008
+ const emit = logger.error ?? logger.log;
2009
+ issues.forEach((m) => {
2010
+ emit(m);
2011
+ });
2012
+ if (merged.strict) {
2013
+ // Deterministic failure under strict mode
2014
+ process.exit(1);
2015
+ }
2016
+ }
2017
+ }
2018
+ catch {
2019
+ // Be tolerant: validation errors reported above; unexpected failures here
2020
+ // should not crash non-strict flows.
2021
+ }
2022
+ });
2023
+ // Also handle root-level flows (no subcommand) so option-aliases can run
2024
+ // with the same merged options and context without duplicating logic.
2025
+ this.hook('preAction', async (thisCommand) => {
2026
+ const raw = thisCommand.opts();
2027
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2028
+ thisCommand.getDotenvCliOptions =
2029
+ merged;
2030
+ this._setOptionsBag(merged);
2031
+ // Avoid duplicate heavy work if a context is already present.
2032
+ if (!this.getCtx()) {
2033
+ const serviceOptions = getDotenvCliOptions2Options(merged);
2034
+ await this.resolveAndLoad(serviceOptions);
2035
+ try {
2036
+ const ctx = this.getCtx();
2037
+ const dotenv = (ctx?.dotenv ?? {});
2038
+ const sources = await resolveGetDotenvConfigSources(import.meta.url);
2039
+ const issues = validateEnvAgainstSources(dotenv, sources);
2040
+ if (Array.isArray(issues) && issues.length > 0) {
2041
+ const logger = (merged
2042
+ .logger ?? console);
2043
+ const emit = logger.error ?? logger.log;
2044
+ issues.forEach((m) => {
2045
+ emit(m);
2046
+ });
2047
+ if (merged.strict) {
2048
+ process.exit(1);
2049
+ }
2050
+ }
2051
+ }
2052
+ catch {
2053
+ // Tolerate validation side-effects in non-strict mode
2054
+ }
2055
+ }
2056
+ });
2057
+ return this;
2058
+ };
2059
+
2060
+ const dbg = (...args) => {
2061
+ if (process.env.GETDOTENV_DEBUG) {
2062
+ // Use stderr to avoid interfering with stdout assertions
2063
+ console.error('[getdotenv:alias]', ...args);
2064
+ }
2065
+ };
2066
+ const attachParentAlias = (cli, options, _cmd) => {
2067
+ const aliasSpec = typeof options.optionAlias === 'string'
2068
+ ? { flags: options.optionAlias, description: undefined, expand: true }
2069
+ : options.optionAlias;
2070
+ if (!aliasSpec)
2071
+ return;
2072
+ const deriveKey = (flags) => {
2073
+ dbg('install alias option', flags);
2074
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
2075
+ const name = long.replace(/^--/, '');
2076
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
2077
+ };
2078
+ const aliasKey = deriveKey(aliasSpec.flags);
2079
+ // Expose the option on the parent.
2080
+ const desc = aliasSpec.description ??
2081
+ 'alias of cmd subcommand; provide command tokens (variadic)';
2082
+ cli.option(aliasSpec.flags, desc);
2083
+ // Tag the just-added parent option for grouped help rendering.
2084
+ try {
2085
+ const optsArr = cli.options;
2086
+ if (Array.isArray(optsArr) && optsArr.length > 0) {
2087
+ const last = optsArr[optsArr.length - 1];
2088
+ last.__group = 'plugin:cmd';
2089
+ }
2090
+ }
2091
+ catch {
2092
+ /* noop */
2093
+ }
2094
+ // Shared alias executor for either preAction or preSubcommand hooks.
2095
+ // Ensure we only execute once even if both hooks fire in a single parse.
2096
+ let aliasHandled = false;
2097
+ const maybeRunAlias = async (thisCommand) => {
2098
+ dbg('alias:maybe:start');
2099
+ const raw = thisCommand.rawArgs ?? [];
2100
+ const childNames = thisCommand.commands.flatMap((c) => [
2101
+ c.name(),
2102
+ ...c.aliases(),
2103
+ ]);
2104
+ const hasSub = childNames.some((n) => raw.includes(n));
2105
+ // Read alias value from parent opts.
2106
+ const o = thisCommand.opts();
2107
+ const val = o[aliasKey];
2108
+ const provided = typeof val === 'string'
2109
+ ? val.length > 0
2110
+ : Array.isArray(val)
2111
+ ? val.length > 0
2112
+ : false;
2113
+ if (!provided || hasSub) {
2114
+ dbg('alias:maybe:skip', { provided, hasSub });
2115
+ return; // not an alias-only invocation
2116
+ }
2117
+ if (aliasHandled) {
2118
+ dbg('alias:maybe:already-handled');
2119
+ return;
2120
+ }
2121
+ aliasHandled = true;
2122
+ dbg('alias-only invocation detected');
2123
+ // Merge CLI options and resolve dotenv context.
2124
+ const { merged } = resolveCliOptions(o,
2125
+ // cast through unknown to avoid readonly -> mutable incompatibilities
2126
+ baseRootOptionDefaults, process.env.getDotenvCliOptions);
2127
+ const logger = merged.logger ?? console;
2128
+ const serviceOptions = getDotenvCliOptions2Options(merged);
2129
+ await cli.resolveAndLoad(serviceOptions);
2130
+ // Normalize alias value.
2131
+ const joined = typeof val === 'string'
2132
+ ? val
2133
+ : Array.isArray(val)
2134
+ ? val.map(String).join(' ')
2135
+ : '';
2136
+ const input = aliasSpec.expand === false
2137
+ ? joined
2138
+ : (dotenvExpandFromProcessEnv(joined) ?? joined);
2139
+ dbg('resolved input', { input });
2140
+ const resolved = resolveCommand(merged.scripts, input);
2141
+ const lg = logger;
2142
+ if (merged.debug) {
2143
+ (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
2144
+ }
2145
+ const { logger: _omit, ...envBag } = merged;
2146
+ // Test guard: when running under tests, prefer stdio: 'inherit' to avoid
2147
+ // assertions depending on captured stdio; ignore GETDOTENV_STDIO/capture.
2148
+ const underTests = process.env.GETDOTENV_TEST === '1' ||
2149
+ typeof process.env.VITEST_WORKER_ID === 'string';
2150
+ const forceExit = process.env.GETDOTENV_FORCE_EXIT === '1';
2151
+ const capture = !underTests &&
2152
+ (process.env.GETDOTENV_STDIO === 'pipe' ||
2153
+ Boolean(merged.capture));
2154
+ dbg('run:start', { capture, shell: merged.shell });
2155
+ // Prefer explicit env injection: include resolved dotenv map to avoid leaking
2156
+ // parent process.env secrets when exclusions are set.
2157
+ const ctx = cli.getCtx();
2158
+ const dotenv = (ctx?.dotenv ?? {});
2159
+ // Diagnostics: --trace [keys...]
2160
+ const traceOpt = merged.trace;
2161
+ if (traceOpt) {
2162
+ const parentKeys = Object.keys(process.env);
2163
+ const dotenvKeys = Object.keys(dotenv);
2164
+ const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
2165
+ const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
2166
+ const childEnvPreview = {
2167
+ ...process.env,
2168
+ ...dotenv,
2169
+ };
2170
+ for (const k of keys) {
2171
+ const parent = process.env[k];
2172
+ const dot = dotenv[k];
2173
+ const final = childEnvPreview[k];
2174
+ const origin = dot !== undefined
2175
+ ? 'dotenv'
2176
+ : parent !== undefined
2177
+ ? 'parent'
2178
+ : 'unset';
2179
+ // Build redact options and triple bag without undefined-valued fields
2180
+ const redOpts = {};
2181
+ const redFlag = merged.redact;
2182
+ const redPatterns = merged
2183
+ .redactPatterns;
2184
+ if (redFlag)
2185
+ redOpts.redact = true;
2186
+ if (redFlag && Array.isArray(redPatterns))
2187
+ redOpts.redactPatterns = redPatterns;
2188
+ const tripleBag = {};
2189
+ if (parent !== undefined)
2190
+ tripleBag.parent = parent;
2191
+ if (dot !== undefined)
2192
+ tripleBag.dotenv = dot;
2193
+ if (final !== undefined)
2194
+ tripleBag.final = final;
2195
+ const triple = redactTriple(k, tripleBag, redOpts);
2196
+ process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
2197
+ const entOpts = {};
2198
+ const warnEntropy = merged.warnEntropy;
2199
+ const entropyThreshold = merged
2200
+ .entropyThreshold;
2201
+ const entropyMinLength = merged
2202
+ .entropyMinLength;
2203
+ const entropyWhitelist = merged
2204
+ .entropyWhitelist;
2205
+ if (typeof warnEntropy === 'boolean')
2206
+ entOpts.warnEntropy = warnEntropy;
2207
+ if (typeof entropyThreshold === 'number')
2208
+ entOpts.entropyThreshold = entropyThreshold;
2209
+ if (typeof entropyMinLength === 'number')
2210
+ entOpts.entropyMinLength = entropyMinLength;
2211
+ if (Array.isArray(entropyWhitelist))
2212
+ entOpts.entropyWhitelist = entropyWhitelist;
2213
+ maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
2214
+ }
2215
+ }
2216
+ let exitCode = Number.NaN;
2217
+ try {
2218
+ // Resolve shell and preserve argv for Node -e snippets under shell-off.
2219
+ const shellSetting = resolveShell(merged.scripts, input, merged.shell);
2220
+ let commandArg = resolved;
2221
+ /** * Special-case: when shell is OFF and no script alias remap occurred
2222
+ * (resolved === input), treat a Node eval payload as an argv array to
2223
+ * avoid lossy re-tokenization of the code string.
2224
+ *
2225
+ * Examples handled:
2226
+ * "node -e \"console.log(JSON.stringify(...))\""
2227
+ * "node --eval 'console.log(...)'"
2228
+ *
2229
+ * We peel exactly one pair of symmetric outer quotes from the code
2230
+ * argument when present; inner quotes remain untouched.
2231
+ */
2232
+ if (shellSetting === false && resolved === input) {
2233
+ // Helper: strip one symmetric outer quote layer
2234
+ const stripOne = (s) => {
2235
+ if (s.length < 2)
2236
+ return s;
2237
+ const a = s.charAt(0);
2238
+ const b = s.charAt(s.length - 1);
2239
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
2240
+ return symmetric ? s.slice(1, -1) : s;
2241
+ };
2242
+ // Normalize whole input once for robust matching
2243
+ const normalized = stripOne(input.trim());
2244
+ // First try a lightweight regex on the normalized string
2245
+ const m = /^\s*node\s+(--eval|-e)\s+([\s\S]+)$/i.exec(normalized);
2246
+ if (m && typeof m[1] === 'string' && typeof m[2] === 'string') {
2247
+ const evalFlag = m[1];
2248
+ let codeArg = m[2].trim();
2249
+ codeArg = stripOne(codeArg);
2250
+ const flag = evalFlag.startsWith('--') ? '--eval' : '-e';
2251
+ commandArg = ['node', flag, codeArg];
2252
+ }
2253
+ else {
2254
+ // Fallback: tokenize and detect node -e/--eval form
2255
+ const parts = tokenize(input);
2256
+ if (parts.length >= 3) {
2257
+ // Narrow under noUncheckedIndexedAccess
2258
+ const p0 = parts[0];
2259
+ const p1 = parts[1];
2260
+ if (p0?.toLowerCase() === 'node' &&
2261
+ (p1 === '-e' || p1 === '--eval')) {
2262
+ commandArg = parts;
2263
+ }
2264
+ }
2265
+ }
2266
+ }
2267
+ exitCode = await runCommand(commandArg, shellSetting, {
2268
+ env: buildSpawnEnv(process.env, {
2269
+ ...dotenv,
2270
+ getDotenvCliOptions: JSON.stringify(envBag),
2271
+ }),
2272
+ stdio: capture ? 'pipe' : 'inherit',
2273
+ });
2274
+ dbg('run:done', { exitCode });
2275
+ }
2276
+ catch (err) {
2277
+ const code = typeof err.exitCode === 'number'
2278
+ ? err.exitCode
2279
+ : 1;
2280
+ dbg('run:error', { exitCode: code, error: String(err) });
2281
+ if (!underTests) {
2282
+ dbg('process.exit (error path)', { exitCode: code });
2283
+ process.exit(code);
2284
+ }
2285
+ else {
2286
+ dbg('process.exit suppressed for tests (error path)', {
2287
+ exitCode: code,
2288
+ });
2289
+ }
2290
+ return;
2291
+ }
2292
+ if (!Number.isNaN(exitCode)) {
2293
+ dbg('process.exit', { exitCode });
2294
+ process.exit(exitCode);
2295
+ }
2296
+ // Fallback: Some environments may not surface a numeric exitCode even on success.
2297
+ // Always terminate alias-only invocations outside tests to avoid hanging the process,
2298
+ // regardless of capture/GETDOTENV_STDIO. Under tests, suppress to keep the runner alive.
2299
+ if (!underTests) {
2300
+ dbg('process.exit (fallback: non-numeric exitCode)', { exitCode: 0 });
2301
+ process.exit(0);
2302
+ }
2303
+ else {
2304
+ dbg('process.exit (fallback suppressed for tests: non-numeric exitCode)', { exitCode: 0 });
2305
+ }
2306
+ // Optional last-resort guard: force an exit on the next tick when enabled.
2307
+ // Intended for diagnosing environments where the process appears to linger
2308
+ // despite reaching the success/error handlers above. Disabled under tests.
2309
+ if (forceExit) {
2310
+ try {
2311
+ if (process.env.GETDOTENV_DEBUG_VERBOSE) {
2312
+ const getHandles = process._getActiveHandles;
2313
+ const handles = typeof getHandles === 'function' ? getHandles() : [];
2314
+ dbg('active handles before forced exit', {
2315
+ count: Array.isArray(handles) ? handles.length : undefined,
2316
+ });
2317
+ }
2318
+ }
2319
+ catch {
2320
+ // best-effort only
2321
+ }
2322
+ const code = Number.isNaN(exitCode) ? 0 : exitCode;
2323
+ dbg('process.exit (forced)', { exitCode: code });
2324
+ setImmediate(() => process.exit(code));
2325
+ }
2326
+ };
2327
+ // Execute alias-only invocations whether the root handles the action // itself (preAction) or Commander routes to a default subcommand (preSubcommand).
2328
+ cli.hook('preAction', async (thisCommand, _actionCommand) => {
2329
+ await maybeRunAlias(thisCommand);
2330
+ });
2331
+ cli.hook('preSubcommand', async (thisCommand) => {
2332
+ await maybeRunAlias(thisCommand);
2333
+ });
2334
+ };
2335
+
2336
+ /**+ Cmd plugin: executes a command using the current getdotenv CLI context.
2337
+ *
2338
+ * - Joins positional args into a single command string.
2339
+ * - Resolves scripts and shell settings using shared helpers.
2340
+ * - Forwards merged CLI options to subprocesses via
2341
+ * process.env.getDotenvCliOptions for nested CLI behavior. */
2342
+ const cmdPlugin = (options = {}) => definePlugin({
2343
+ id: 'cmd',
2344
+ setup(cli) {
2345
+ const aliasSpec = typeof options.optionAlias === 'string'
2346
+ ? { flags: options.optionAlias}
2347
+ : options.optionAlias;
2348
+ const deriveKey = (flags) => {
2349
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
2350
+ const name = long.replace(/^--/, '');
2351
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
2352
+ };
2353
+ const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
2354
+ const cmd = new Command()
2355
+ .name('cmd')
2356
+ .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
2357
+ .configureHelp({ showGlobalOptions: true })
2358
+ .enablePositionalOptions()
2359
+ .passThroughOptions()
2360
+ .argument('[command...]')
2361
+ .action(async (commandParts, _opts, thisCommand) => {
2362
+ // Commander passes positional tokens as the first action argument
2363
+ const args = Array.isArray(commandParts) ? commandParts : [];
2364
+ // No-op when invoked as the default command with no args.
2365
+ if (args.length === 0)
2366
+ return;
2367
+ const parent = thisCommand.parent;
2368
+ if (!parent)
2369
+ throw new Error('parent command not found'); // Conflict detection: if an alias option is present on parent, do not
2370
+ // also accept positional cmd args.
2371
+ if (aliasKey) {
2372
+ const pv = parent.opts();
2373
+ const ov = pv[aliasKey];
2374
+ if (ov !== undefined) {
2375
+ const merged = parent.getDotenvCliOptions ?? {};
2376
+ const logger = merged.logger ?? console;
2377
+ const lr = logger;
2378
+ const emit = lr.error ?? lr.log;
2379
+ emit(`--${aliasKey} option conflicts with cmd subcommand.`);
2380
+ process.exit(0);
2381
+ }
2382
+ }
2383
+ // Merged CLI options are persisted by the shipped CLI preSubcommand hook.
2384
+ const merged = parent.getDotenvCliOptions ?? {};
2385
+ const logger = merged.logger ?? console;
2386
+ // Join positional args into the command string.
2387
+ const input = args.map(String).join(' ');
2388
+ // Resolve command and shell using shared helpers.
2389
+ const scripts = merged.scripts;
2390
+ const shell = merged.shell;
2391
+ const resolved = resolveCommand(scripts, input);
2392
+ if (merged.debug) {
2393
+ const lg = logger;
2394
+ (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
2395
+ }
2396
+ // Round-trip CLI options for nested getdotenv invocations.
2397
+ // Omit logger (functions are not serializable).
2398
+ const { logger: _omit, ...envBag } = merged;
2399
+ const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
2400
+ Boolean(merged.capture);
2401
+ // Prefer explicit env injection: pass the resolved dotenv map to the child.
2402
+ // This avoids leaking prior secrets from the parent process.env when
2403
+ // exclusions (e.g., --exclude-private) are in effect.
2404
+ const host = cli;
2405
+ const ctx = host.getCtx();
2406
+ const dotenv = (ctx?.dotenv ?? {});
2407
+ // Diagnostics: --trace [keys...] (space-delimited keys if provided; all keys when true)
2408
+ const traceOpt = merged.trace;
2409
+ if (traceOpt) {
2410
+ // Determine keys to trace: all keys (parent ∪ dotenv) or selected.
2411
+ const parentKeys = Object.keys(process.env);
2412
+ const dotenvKeys = Object.keys(dotenv);
2413
+ const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
2414
+ const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
2415
+ // Child env preview (as composed below; excluding getDotenvCliOptions)
2416
+ const childEnvPreview = {
2417
+ ...process.env,
2418
+ ...dotenv,
2419
+ };
2420
+ for (const k of keys) {
2421
+ const parent = process.env[k];
2422
+ const dot = dotenv[k];
2423
+ const final = childEnvPreview[k];
2424
+ const origin = dot !== undefined
2425
+ ? 'dotenv'
2426
+ : parent !== undefined
2427
+ ? 'parent'
2428
+ : 'unset';
2429
+ // Apply presentation-time redaction (if enabled)
2430
+ const redFlag = merged.redact;
2431
+ const redPatterns = merged
2432
+ .redactPatterns;
2433
+ const redOpts = {};
2434
+ if (redFlag)
2435
+ redOpts.redact = true;
2436
+ if (redFlag && Array.isArray(redPatterns))
2437
+ redOpts.redactPatterns = redPatterns;
2438
+ const tripleBag = {};
2439
+ if (parent !== undefined)
2440
+ tripleBag.parent = parent;
2441
+ if (dot !== undefined)
2442
+ tripleBag.dotenv = dot;
2443
+ if (final !== undefined)
2444
+ tripleBag.final = final;
2445
+ const triple = redactTriple(k, tripleBag, redOpts);
2446
+ // Emit concise diagnostic line to stderr.
2447
+ process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
2448
+ // Optional entropy warning (once-per-key)
2449
+ const entOpts = {};
2450
+ const warnEntropy = merged
2451
+ .warnEntropy;
2452
+ const entropyThreshold = merged.entropyThreshold;
2453
+ const entropyMinLength = merged.entropyMinLength;
2454
+ const entropyWhitelist = merged.entropyWhitelist;
2455
+ if (typeof warnEntropy === 'boolean')
2456
+ entOpts.warnEntropy = warnEntropy;
2457
+ if (typeof entropyThreshold === 'number')
2458
+ entOpts.entropyThreshold = entropyThreshold;
2459
+ if (typeof entropyMinLength === 'number')
2460
+ entOpts.entropyMinLength = entropyMinLength;
2461
+ if (Array.isArray(entropyWhitelist))
2462
+ entOpts.entropyWhitelist = entropyWhitelist;
2463
+ maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
2464
+ }
2465
+ }
2466
+ const shellSetting = resolveShell(scripts, input, shell);
2467
+ /**
2468
+ * Preserve original argv array when:
2469
+ * - shell is OFF (plain execa), and
2470
+ * - no script alias remap occurred (resolved === input).
2471
+ *
2472
+ * This avoids lossy re-tokenization of code snippets such as:
2473
+ * node -e "console.log(process.env.APP_SECRET ?? '')"
2474
+ * where quotes may have been stripped by the parent shell and
2475
+ * spaces inside the code must remain a single argument.
2476
+ */
2477
+ const commandArg = shellSetting === false && resolved === input
2478
+ ? args.map(String)
2479
+ : resolved;
2480
+ await runCommand(commandArg, shellSetting, {
2481
+ env: buildSpawnEnv(process.env, {
2482
+ ...dotenv,
2483
+ getDotenvCliOptions: JSON.stringify(envBag),
2484
+ }),
2485
+ stdio: capture ? 'pipe' : 'inherit',
2486
+ });
2487
+ });
2488
+ if (options.asDefault)
2489
+ cli.addCommand(cmd, { isDefault: true });
2490
+ else
2491
+ cli.addCommand(cmd);
2492
+ // Parent-attached option alias (optional).
2493
+ if (aliasSpec)
2494
+ attachParentAlias(cli, options);
2495
+ },
2496
+ });
2497
+
2498
+ export { cmdPlugin };