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