@karmaniverous/get-dotenv 5.2.4 → 5.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,8 @@
1
- import { Command, Option } from 'commander';
1
+ import { Command } from 'commander';
2
2
  import { execa, execaCommand } from 'execa';
3
- import fs from 'fs-extra';
4
- import { packageDirectory } from 'package-directory';
5
- import url, { fileURLToPath, pathToFileURL } from 'url';
6
- import path, { join, extname } from 'path';
7
- import { z } from 'zod';
8
- import YAML from 'yaml';
9
- import { nanoid } from 'nanoid';
10
- import { parse } from 'dotenv';
11
- import { createHash } from 'crypto';
3
+ import 'fs-extra';
4
+ import 'package-directory';
5
+ import 'path';
12
6
 
13
7
  // Minimal tokenizer for shell-off execution:
14
8
  // Splits by whitespace while preserving quoted segments (single or double quotes).
@@ -275,19 +269,6 @@ const DEFAULT_PATTERNS = [
275
269
  const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
276
270
  const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
277
271
  const MASK = '[redacted]';
278
- /**
279
- * Produce a shallow redacted copy of an env-like object for display.
280
- */
281
- const redactObject = (obj, opts) => {
282
- if (!opts?.redact)
283
- return { ...obj };
284
- const regs = compile(opts.redactPatterns);
285
- const out = {};
286
- for (const [k, v] of Object.entries(obj)) {
287
- out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
288
- }
289
- return out;
290
- };
291
272
  /**
292
273
  * Utility to redact three related displayed values (parent/dotenv/final)
293
274
  * consistently for trace lines.
@@ -365,10 +346,8 @@ const baseRootOptionDefaults = {
365
346
  // (debug/log/exclude* resolved via flag utils)
366
347
  };
367
348
 
368
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
369
-
370
349
  /** @internal */
371
- const isPlainObject$1 = (value) => value !== null &&
350
+ const isPlainObject = (value) => value !== null &&
372
351
  typeof value === 'object' &&
373
352
  Object.getPrototypeOf(value) === Object.prototype;
374
353
  const mergeInto = (target, source) => {
@@ -376,10 +355,10 @@ const mergeInto = (target, source) => {
376
355
  if (sVal === undefined)
377
356
  continue; // do not overwrite with undefined
378
357
  const tVal = target[key];
379
- if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
358
+ if (isPlainObject(tVal) && isPlainObject(sVal)) {
380
359
  target[key] = mergeInto({ ...tVal }, sVal);
381
360
  }
382
- else if (isPlainObject$1(sVal)) {
361
+ else if (isPlainObject(sVal)) {
383
362
  target[key] = mergeInto({}, sVal);
384
363
  }
385
364
  else {
@@ -409,370 +388,129 @@ const defaultsDeep = (...layers) => {
409
388
  return result;
410
389
  };
411
390
 
412
- // src/GetDotenvOptions.ts
413
- const getDotenvOptionsFilename = 'getdotenv.config.json';
414
391
  /**
415
- * Converts programmatic CLI options to `getDotenv` options. *
416
- * @param cliOptions - CLI options. Defaults to `{}`.
392
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
393
+ * - If the user explicitly enabled the flag, return true.
394
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
395
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
417
396
  *
418
- * @returns `getDotenv` options.
397
+ * @param exclude - The "on" flag value as parsed by Commander.
398
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
399
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
400
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * resolveExclusion(undefined, undefined, true); // => true
405
+ * ```
419
406
  */
420
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
421
- /**
422
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
423
- *
424
- * - 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`
425
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
426
- * - Drops CLI-only keys that have no programmatic equivalent.
427
- *
428
- * @remarks
429
- * Follows exact-optional semantics by not emitting undefined-valued entries.
430
- */
431
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
432
- // Create a shallow copy then delete optional CLI-only keys if present.
433
- const restObj = { ...rest };
434
- delete restObj.debug;
435
- delete restObj.scripts;
436
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
437
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
438
- let parsedVars;
439
- if (typeof vars === 'string') {
440
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
441
- ? RegExp(varsAssignorPattern)
442
- : (varsAssignor ?? '=')));
443
- parsedVars = Object.fromEntries(kvPairs);
444
- }
445
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
446
- // Keep only string or undefined values to match ProcessEnv.
447
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
448
- parsedVars = Object.fromEntries(entries);
449
- }
450
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
451
- // expectations and the compat test assertions.
452
- if (parsedVars) {
453
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
454
- }
455
- // Tolerate paths as either a delimited string or string[]
456
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
457
- // under the RootOptionsShape (which declares paths as string | undefined).
458
- const pathsAny = paths;
459
- const pathsOut = Array.isArray(pathsAny)
460
- ? pathsAny.filter((p) => typeof p === 'string')
461
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
462
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
463
- return {
464
- ...restObj,
465
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
466
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
467
- };
468
- };
469
- const resolveGetDotenvOptions = async (customOptions) => {
470
- /**
471
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
472
- *
473
- * 1. Base defaults derived from the CLI generator defaults
474
- * ({@link baseGetDotenvCliOptions}).
475
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
476
- * package root (if present).
477
- * 3. The provided {@link customOptions}.
478
- *
479
- * The result preserves explicit empty values and drops only `undefined`.
480
- *
481
- * @returns Fully-resolved {@link GetDotenvOptions}.
482
- *
483
- * @example
484
- * ```ts
485
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
486
- * ```
487
- */
488
- const localPkgDir = await packageDirectory();
489
- const localOptionsPath = localPkgDir
490
- ? join(localPkgDir, getDotenvOptionsFilename)
491
- : undefined;
492
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
493
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
494
- : {});
495
- // Merge order: base < local < custom (custom has highest precedence)
496
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
497
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
498
- const result = defaultsDeep(defaultsFromCli, customOptions);
499
- return {
500
- ...result, // Keep explicit empty strings/zeros; drop only undefined
501
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
502
- };
503
- };
504
-
407
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
505
408
  /**
506
- * Zod schemas for programmatic GetDotenv options.
409
+ * Resolve an optional flag with "--exclude-all" overrides.
410
+ * If excludeAll is set and the individual "...-off" is not, force true.
411
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
412
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
413
+ *
414
+ * @param exclude - Individual include/exclude flag.
415
+ * @param excludeOff - Individual "...-off" flag.
416
+ * @param defaultValue - Default for the individual flag.
417
+ * @param excludeAll - Global "exclude-all" flag.
418
+ * @param excludeAllOff - Global "exclude-all-off" flag.
507
419
  *
508
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
509
- * Legacy paths continue to use existing types/logic. The new plugin host will
510
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
511
- * later per the staged plan.
420
+ * @example
421
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
512
422
  */
513
- // Minimal process env representation: string values or undefined to indicate "unset".
514
- const processEnvSchema = z.record(z.string(), z.string().optional());
515
- // RAW: all fields optional — undefined means "inherit" from lower layers.
516
- const getDotenvOptionsSchemaRaw = z.object({
517
- defaultEnv: z.string().optional(),
518
- dotenvToken: z.string().optional(),
519
- dynamicPath: z.string().optional(),
520
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
521
- dynamic: z.record(z.string(), z.unknown()).optional(),
522
- env: z.string().optional(),
523
- excludeDynamic: z.boolean().optional(),
524
- excludeEnv: z.boolean().optional(),
525
- excludeGlobal: z.boolean().optional(),
526
- excludePrivate: z.boolean().optional(),
527
- excludePublic: z.boolean().optional(),
528
- loadProcess: z.boolean().optional(),
529
- log: z.boolean().optional(),
530
- outputPath: z.string().optional(),
531
- paths: z.array(z.string()).optional(),
532
- privateToken: z.string().optional(),
533
- vars: processEnvSchema.optional(),
534
- // Host-only feature flag: guarded integration of config loader/overlay
535
- useConfigLoader: z.boolean().optional(),
536
- });
537
- // RESOLVED: service-boundary contract (post-inheritance).
538
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
539
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
540
-
423
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
424
+ // Order of precedence:
425
+ // 1) Individual explicit "on" wins outright.
426
+ // 2) Individual explicit "off" wins over any global.
427
+ // 3) Global exclude-all forces true when not explicitly turned off.
428
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
429
+ // 5) Fall back to the default (true => set; false/undefined => unset).
430
+ (() => {
431
+ // Individual "on"
432
+ if (exclude === true)
433
+ return true;
434
+ // Individual "off"
435
+ if (excludeOff === true)
436
+ return undefined;
437
+ // Global "exclude-all" ON (unless explicitly turned off)
438
+ if (excludeAll === true)
439
+ return true;
440
+ // Global "exclude-all-off" (unless explicitly enabled)
441
+ if (excludeAllOff === true)
442
+ return undefined;
443
+ // Default
444
+ return defaultValue ? true : undefined;
445
+ })();
541
446
  /**
542
- * Zod schemas for configuration files discovered by the new loader.
447
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
448
+ * delete when undefined; assign when defined — without requiring an index signature on T.
449
+ *
450
+ * @typeParam T - Target object type.
451
+ * @param obj - The object to write to.
452
+ * @param key - The optional boolean property key of {@link T}.
453
+ * @param value - The value to set or `undefined` to unset.
543
454
  *
544
- * Notes:
545
- * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
546
- * - RESOLVED: normalized shapes (paths always string[]).
547
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
455
+ * @remarks
456
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
548
457
  */
549
- // String-only env value map
550
- const stringMap = z.record(z.string(), z.string());
551
- const envStringMap = z.record(z.string(), stringMap);
552
- // Allow string[] or single string for "paths" in RAW; normalize later.
553
- const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
554
- const getDotenvConfigSchemaRaw = z.object({
555
- dotenvToken: z.string().optional(),
556
- privateToken: z.string().optional(),
557
- paths: rawPathsSchema,
558
- loadProcess: z.boolean().optional(),
559
- log: z.boolean().optional(),
560
- shell: z.union([z.string(), z.boolean()]).optional(),
561
- scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
562
- requiredKeys: z.array(z.string()).optional(),
563
- schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
564
- vars: stringMap.optional(), // public, global
565
- envVars: envStringMap.optional(), // public, per-env
566
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
567
- dynamic: z.unknown().optional(),
568
- // Per-plugin config bag; validated by plugins/host when used.
569
- plugins: z.record(z.string(), z.unknown()).optional(),
570
- });
571
- // Normalize paths to string[]
572
- const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
573
- const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
574
- ...raw,
575
- paths: normalizePaths(raw.paths),
576
- }));
577
-
578
- // Discovery candidates (first match wins per scope/privacy).
579
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
580
- const PUBLIC_FILENAMES = [
581
- 'getdotenv.config.json',
582
- 'getdotenv.config.yaml',
583
- 'getdotenv.config.yml',
584
- 'getdotenv.config.js',
585
- 'getdotenv.config.mjs',
586
- 'getdotenv.config.cjs',
587
- 'getdotenv.config.ts',
588
- 'getdotenv.config.mts',
589
- 'getdotenv.config.cts',
590
- ];
591
- const LOCAL_FILENAMES = [
592
- 'getdotenv.config.local.json',
593
- 'getdotenv.config.local.yaml',
594
- 'getdotenv.config.local.yml',
595
- 'getdotenv.config.local.js',
596
- 'getdotenv.config.local.mjs',
597
- 'getdotenv.config.local.cjs',
598
- 'getdotenv.config.local.ts',
599
- 'getdotenv.config.local.mts',
600
- 'getdotenv.config.local.cts',
601
- ];
602
- const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
603
- const isJson = (p) => extname(p).toLowerCase() === '.json';
604
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
605
- // --- Internal JS/TS module loader helpers (default export) ---
606
- const importDefault$1 = async (fileUrl) => {
607
- const mod = (await import(fileUrl));
608
- return mod.default;
609
- };
610
- const cacheName = (absPath, suffix) => {
611
- // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
612
- const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
613
- return `${base}.${suffix}.mjs`;
614
- };
615
- const ensureDir = async (dir) => {
616
- await fs.ensureDir(dir);
617
- return dir;
618
- };
619
- const loadJsTsDefault = async (absPath) => {
620
- const fileUrl = pathToFileURL(absPath).toString();
621
- const ext = extname(absPath).toLowerCase();
622
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
623
- return importDefault$1(fileUrl);
624
- }
625
- // Try direct import first in case a TS loader is active.
626
- try {
627
- const val = await importDefault$1(fileUrl);
628
- if (val)
629
- return val;
630
- }
631
- catch {
632
- /* fallthrough */
633
- }
634
- // esbuild bundle to a temp ESM file
635
- try {
636
- const esbuild = (await import('esbuild'));
637
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
638
- const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
639
- await esbuild.build({
640
- entryPoints: [absPath],
641
- bundle: true,
642
- platform: 'node',
643
- format: 'esm',
644
- target: 'node20',
645
- outfile,
646
- sourcemap: false,
647
- logLevel: 'silent',
648
- });
649
- return await importDefault$1(pathToFileURL(outfile).toString());
650
- }
651
- catch {
652
- /* fallthrough to TS transpile */
653
- }
654
- // typescript.transpileModule simple transpile (single-file)
655
- try {
656
- const ts = (await import('typescript'));
657
- const src = await fs.readFile(absPath, 'utf-8');
658
- const out = ts.transpileModule(src, {
659
- compilerOptions: {
660
- module: 'ESNext',
661
- target: 'ES2022',
662
- moduleResolution: 'NodeNext',
663
- },
664
- }).outputText;
665
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
666
- const outfile = path.join(outDir, cacheName(absPath, 'ts'));
667
- await fs.writeFile(outfile, out, 'utf-8');
668
- return await importDefault$1(pathToFileURL(outfile).toString());
669
- }
670
- catch {
671
- throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
672
- }
673
- };
674
- /**
675
- * Discover JSON/YAML config files in the packaged root and project root.
676
- * Order: packaged public → project public → project local. */
677
- const discoverConfigFiles = async (importMetaUrl) => {
678
- const files = [];
679
- // Packaged root via importMetaUrl (optional)
680
- if (importMetaUrl) {
681
- const fromUrl = fileURLToPath(importMetaUrl);
682
- const packagedRoot = await packageDirectory({ cwd: fromUrl });
683
- if (packagedRoot) {
684
- for (const name of PUBLIC_FILENAMES) {
685
- const p = join(packagedRoot, name);
686
- if (await fs.pathExists(p)) {
687
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
688
- break; // only one public file expected per scope
689
- }
690
- }
691
- // By policy, packaged .local is not expected; skip even if present.
692
- }
693
- }
694
- // Project root (from current working directory)
695
- const projectRoot = await packageDirectory();
696
- if (projectRoot) {
697
- for (const name of PUBLIC_FILENAMES) {
698
- const p = join(projectRoot, name);
699
- if (await fs.pathExists(p)) {
700
- files.push({ path: p, privacy: 'public', scope: 'project' });
701
- break;
702
- }
703
- }
704
- for (const name of LOCAL_FILENAMES) {
705
- const p = join(projectRoot, name);
706
- if (await fs.pathExists(p)) {
707
- files.push({ path: p, privacy: 'local', scope: 'project' });
708
- break;
709
- }
710
- }
711
- }
712
- return files;
458
+ const setOptionalFlag = (obj, key, value) => {
459
+ const target = obj;
460
+ const k = key;
461
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
462
+ if (value === undefined)
463
+ delete target[k];
464
+ else
465
+ target[k] = value;
713
466
  };
467
+
714
468
  /**
715
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
716
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
717
- *
718
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
719
- * For JS/TS: default export is loaded; "dynamic" is allowed.
469
+ * Merge and normalize raw Commander options (current + parent + defaults)
470
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
471
+ * avoid cross-layer coupling; callers may cast as needed.
720
472
  */
721
- const loadConfigFile = async (filePath) => {
722
- let raw = {};
723
- try {
724
- const abs = path.resolve(filePath);
725
- if (isJsOrTs(abs)) {
726
- // JS/TS support: load default export via robust pipeline.
727
- const mod = await loadJsTsDefault(abs);
728
- raw = mod ?? {};
473
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
474
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
475
+ ? JSON.parse(parentJson)
476
+ : undefined;
477
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
478
+ const current = { ...rest };
479
+ if (typeof scripts === 'string') {
480
+ try {
481
+ current.scripts = JSON.parse(scripts);
729
482
  }
730
- else {
731
- const txt = await fs.readFile(abs, 'utf-8');
732
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
483
+ catch {
484
+ // ignore parse errors; leave scripts undefined
733
485
  }
734
486
  }
735
- catch (err) {
736
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
737
- }
738
- // Validate RAW
739
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
740
- if (!parsed.success) {
741
- const msgs = parsed.error.issues
742
- .map((i) => `${i.path.join('.')}: ${i.message}`)
743
- .join('\n');
744
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
745
- }
746
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
747
- if (!isJsOrTs(filePath) &&
748
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
749
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
750
- `Use JS/TS config for "dynamic" or "schema".`);
487
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
488
+ const d = defaults;
489
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
490
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
491
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
492
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
493
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
494
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
495
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
496
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
497
+ // warnEntropy (tri-state)
498
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
499
+ // Normalize shell for predictability: explicit default shell per OS.
500
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
501
+ let resolvedShell = merged.shell;
502
+ if (shellOff)
503
+ resolvedShell = false;
504
+ else if (resolvedShell === true || resolvedShell === undefined) {
505
+ resolvedShell = defaultShell;
751
506
  }
752
- return getDotenvConfigSchemaResolved.parse(parsed.data);
753
- };
754
- /**
755
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
756
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
757
- */
758
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
759
- const discovered = await discoverConfigFiles(importMetaUrl);
760
- const result = {};
761
- for (const f of discovered) {
762
- const cfg = await loadConfigFile(f.path);
763
- if (f.scope === 'packaged') {
764
- // packaged public only
765
- result.packaged = cfg;
766
- }
767
- else {
768
- result.project ??= {};
769
- if (f.privacy === 'public')
770
- result.project.public = cfg;
771
- else
772
- result.project.local = cfg;
773
- }
507
+ else if (typeof resolvedShell !== 'string' &&
508
+ typeof defaults.shell === 'string') {
509
+ resolvedShell = defaults.shell;
774
510
  }
775
- return result;
511
+ merged.shell = resolvedShell;
512
+ const cmd = typeof command === 'string' ? command : undefined;
513
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
776
514
  };
777
515
 
778
516
  /**
@@ -861,39 +599,6 @@ const dotenvExpand = (value, ref = process.env) => {
861
599
  const result = interpolate(value, ref);
862
600
  return result ? result.replace(/\\\$/g, '$') : undefined;
863
601
  };
864
- /**
865
- * Recursively expands environment variables in the values of a JSON object.
866
- * Variables may be presented with optional default as `$VAR[:default]` or
867
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
868
- *
869
- * @param values - The values object to expand.
870
- * @param options - Expansion options.
871
- * @returns The value object with expanded string values.
872
- *
873
- * @example
874
- * ```ts
875
- * process.env.FOO = 'bar';
876
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
877
- * // => { A: "bar", B: "xbary" }
878
- * ```
879
- *
880
- * @remarks
881
- * Options:
882
- * - ref: The reference object to use for expansion (defaults to process.env).
883
- * - progressive: Whether to progressively add expanded values to the set of
884
- * reference keys.
885
- *
886
- * When `progressive` is true, each expanded key becomes available for
887
- * subsequent expansions in the same object (left-to-right by object key order).
888
- */
889
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
890
- const { ref = process.env, progressive = false } = options;
891
- acc[key] = dotenvExpand(values[key], {
892
- ...ref,
893
- ...(progressive ? acc : {}),
894
- });
895
- return acc;
896
- }, {});
897
602
  /**
898
603
  * Recursively expands environment variables in a string using `process.env` as
899
604
  * the expansion reference. Variables may be presented with optional default as
@@ -911,1157 +616,61 @@ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduc
911
616
  */
912
617
  const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
913
618
 
914
- const applyKv = (current, kv) => {
915
- if (!kv || Object.keys(kv).length === 0)
916
- return current;
917
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
918
- return { ...current, ...expanded };
919
- };
920
- const applyConfigSlice = (current, cfg, env) => {
921
- if (!cfg)
922
- return current;
923
- // kind axis: global then env (env overrides global)
924
- const afterGlobal = applyKv(current, cfg.vars);
925
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
926
- return applyKv(afterGlobal, envKv);
927
- };
928
- /**
929
- * Overlay config-provided values onto a base ProcessEnv using precedence axes:
930
- * - kind: env \> global
931
- * - privacy: local \> public
932
- * - source: project \> packaged \> base
933
- *
934
- * Programmatic explicit vars (if provided) override all config slices.
935
- * Progressive expansion is applied within each slice.
936
- */
937
- const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
938
- let current = { ...base };
939
- // Source: packaged (public -> local)
940
- current = applyConfigSlice(current, configs.packaged, env);
941
- // Packaged "local" is not expected by policy; if present, honor it.
942
- // We do not have a separate object for packaged.local in sources, keep as-is.
943
- // Source: project (public -> local)
944
- current = applyConfigSlice(current, configs.project?.public, env);
945
- current = applyConfigSlice(current, configs.project?.local, env);
946
- // Programmatic explicit vars (top of static tier)
947
- if (programmaticVars) {
948
- const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
949
- current = applyKv(current, toApply);
950
- }
951
- return current;
952
- };
953
-
619
+ // src/GetDotenvOptions.ts
954
620
  /**
955
- * Asynchronously read a dotenv file & parse it into an object.
621
+ * Converts programmatic CLI options to `getDotenv` options. *
622
+ * @param cliOptions - CLI options. Defaults to `{}`.
956
623
  *
957
- * @param path - Path to dotenv file.
958
- * @returns The parsed dotenv object.
624
+ * @returns `getDotenv` options.
959
625
  */
960
- const readDotenv = async (path) => {
961
- try {
962
- return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
963
- }
964
- catch {
965
- return {};
966
- }
967
- };
968
-
969
- const importDefault = async (fileUrl) => {
970
- const mod = (await import(fileUrl));
971
- return mod.default;
972
- };
973
- const cacheHash = (absPath, mtimeMs) => createHash('sha1')
974
- .update(absPath)
975
- .update(String(mtimeMs))
976
- .digest('hex')
977
- .slice(0, 12);
978
- /**
979
- * Remove older compiled cache files for a given source base name, keeping
980
- * at most `keep` most-recent files. Errors are ignored by design.
981
- */
982
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
983
- try {
984
- const entries = await fs.readdir(cacheDir);
985
- const mine = entries
986
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
987
- .map((f) => path.join(cacheDir, f));
988
- if (mine.length <= keep)
989
- return;
990
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
991
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
992
- const toDelete = stats.slice(keep).map((s) => s.p);
993
- await Promise.all(toDelete.map(async (p) => {
994
- try {
995
- await fs.remove(p);
996
- }
997
- catch {
998
- // best-effort cleanup
999
- }
1000
- }));
1001
- }
1002
- catch {
1003
- // best-effort cleanup
1004
- }
1005
- };
1006
- /**
1007
- * Load a module default export from a JS/TS file with robust fallbacks:
1008
- * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1009
- * 1) try direct import (if a TS loader is active),
1010
- * 2) esbuild bundle to a temp ESM file,
1011
- * 3) typescript.transpileModule fallback for simple modules.
1012
- *
1013
- * @param absPath - absolute path to source file
1014
- * @param cacheDirName - cache subfolder under .tsbuild
1015
- */
1016
- const loadModuleDefault = async (absPath, cacheDirName) => {
1017
- const ext = path.extname(absPath).toLowerCase();
1018
- const fileUrl = url.pathToFileURL(absPath).toString();
1019
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1020
- return importDefault(fileUrl);
1021
- }
1022
- // Try direct import first (TS loader active)
1023
- try {
1024
- const dyn = await importDefault(fileUrl);
1025
- if (dyn)
1026
- return dyn;
1027
- }
1028
- catch {
1029
- /* fall through */
1030
- }
1031
- const stat = await fs.stat(absPath);
1032
- const hash = cacheHash(absPath, stat.mtimeMs);
1033
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
1034
- await fs.ensureDir(cacheDir);
1035
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
1036
- // Try esbuild
1037
- try {
1038
- const esbuild = (await import('esbuild'));
1039
- await esbuild.build({
1040
- entryPoints: [absPath],
1041
- bundle: true,
1042
- platform: 'node',
1043
- format: 'esm',
1044
- target: 'node20',
1045
- outfile: cacheFile,
1046
- sourcemap: false,
1047
- logLevel: 'silent',
1048
- });
1049
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1050
- // Best-effort: trim older cache files for this source.
1051
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1052
- return result;
1053
- }
1054
- catch {
1055
- /* fall through to TS transpile */
1056
- }
1057
- // TypeScript transpile fallback
1058
- try {
1059
- const ts = (await import('typescript'));
1060
- const code = await fs.readFile(absPath, 'utf-8');
1061
- const out = ts.transpileModule(code, {
1062
- compilerOptions: {
1063
- module: 'ESNext',
1064
- target: 'ES2022',
1065
- moduleResolution: 'NodeNext',
1066
- },
1067
- }).outputText;
1068
- await fs.writeFile(cacheFile, out, 'utf-8');
1069
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1070
- // Best-effort: trim older cache files for this source.
1071
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1072
- return result;
1073
- }
1074
- catch {
1075
- // Caller decides final error wording; rethrow for upstream mapping.
1076
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
1077
- }
1078
- };
1079
-
1080
- /**
1081
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
1082
- *
1083
- * @param options - `GetDotenvOptions` object
1084
- * @returns The combined parsed dotenv object.
1085
- * * @example Load from the project root with default tokens
1086
- * ```ts
1087
- * const vars = await getDotenv();
1088
- * console.log(vars.MY_SETTING);
1089
- * ```
1090
- *
1091
- * @example Load from multiple paths and a specific environment
1092
- * ```ts
1093
- * const vars = await getDotenv({
1094
- * env: 'dev',
1095
- * dotenvToken: '.testenv',
1096
- * privateToken: 'secret',
1097
- * paths: ['./', './packages/app'],
1098
- * });
1099
- * ```
1100
- *
1101
- * @example Use dynamic variables
1102
- * ```ts
1103
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
1104
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
1105
- * ```
1106
- *
1107
- * @remarks
1108
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
1109
- * into `process.env` as a side effect.
1110
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
1111
- * The path is resolved after expansion, so it may reference previously loaded vars.
1112
- *
1113
- * @throws Error when a dynamic module is present but cannot be imported.
1114
- * @throws Error when an output path was requested but could not be resolved.
1115
- */
1116
- const getDotenv = async (options = {}) => {
1117
- // Apply defaults.
1118
- 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);
1119
- // Read .env files.
1120
- const loaded = paths.length
1121
- ? await paths.reduce(async (e, p) => {
1122
- const publicGlobal = excludePublic || excludeGlobal
1123
- ? Promise.resolve({})
1124
- : readDotenv(path.resolve(p, dotenvToken));
1125
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1126
- ? Promise.resolve({})
1127
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1128
- const privateGlobal = excludePrivate || excludeGlobal
1129
- ? Promise.resolve({})
1130
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1131
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1132
- ? Promise.resolve({})
1133
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1134
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1135
- e,
1136
- publicGlobal,
1137
- publicEnv,
1138
- privateGlobal,
1139
- privateEnv,
1140
- ]);
1141
- return {
1142
- ...eResolved,
1143
- ...publicGlobalResolved,
1144
- ...publicEnvResolved,
1145
- ...privateGlobalResolved,
1146
- ...privateEnvResolved,
1147
- };
1148
- }, Promise.resolve({}))
1149
- : {};
1150
- const outputKey = nanoid();
1151
- const dotenv = dotenvExpandAll({
1152
- ...loaded,
1153
- ...vars,
1154
- ...(outputPath ? { [outputKey]: outputPath } : {}),
1155
- }, { progressive: true });
1156
- // Process dynamic variables. Programmatic option takes precedence over path.
1157
- if (!excludeDynamic) {
1158
- let dynamic = undefined;
1159
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1160
- dynamic = options.dynamic;
1161
- }
1162
- else if (dynamicPath) {
1163
- const absDynamicPath = path.resolve(dynamicPath);
1164
- if (await fs.exists(absDynamicPath)) {
1165
- try {
1166
- dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1167
- }
1168
- catch {
1169
- // Preserve legacy error text for compatibility with tests/docs.
1170
- throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1171
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1172
- }
1173
- }
1174
- }
1175
- if (dynamic) {
1176
- try {
1177
- for (const key in dynamic)
1178
- Object.assign(dotenv, {
1179
- [key]: typeof dynamic[key] === 'function'
1180
- ? dynamic[key](dotenv, env ?? defaultEnv)
1181
- : dynamic[key],
1182
- });
1183
- }
1184
- catch {
1185
- throw new Error(`Unable to evaluate dynamic variables.`);
1186
- }
1187
- }
1188
- }
1189
- // Write output file.
1190
- let resultDotenv = dotenv;
1191
- if (outputPath) {
1192
- const outputPathResolved = dotenv[outputKey];
1193
- if (!outputPathResolved)
1194
- throw new Error('Output path not found.');
1195
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1196
- await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
1197
- const value = dotenvForOutput[key] ?? '';
1198
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1199
- }, ''), { encoding: 'utf-8' });
1200
- resultDotenv = dotenvForOutput;
1201
- }
1202
- // Log result.
1203
- if (log) {
1204
- const redactFlag = options.redact ?? false;
1205
- const redactPatterns = options.redactPatterns ?? undefined;
1206
- const redOpts = {};
1207
- if (redactFlag)
1208
- redOpts.redact = true;
1209
- if (redactFlag && Array.isArray(redactPatterns))
1210
- redOpts.redactPatterns = redactPatterns;
1211
- const bag = redactFlag
1212
- ? redactObject(resultDotenv, redOpts)
1213
- : { ...resultDotenv };
1214
- logger.log(bag);
1215
- // Entropy warnings: once-per-key-per-run (presentation only)
1216
- const warnEntropyVal = options.warnEntropy ?? true;
1217
- const entropyThresholdVal = options
1218
- .entropyThreshold;
1219
- const entropyMinLengthVal = options
1220
- .entropyMinLength;
1221
- const entropyWhitelistVal = options
1222
- .entropyWhitelist;
1223
- const entOpts = {};
1224
- if (typeof warnEntropyVal === 'boolean')
1225
- entOpts.warnEntropy = warnEntropyVal;
1226
- if (typeof entropyThresholdVal === 'number')
1227
- entOpts.entropyThreshold = entropyThresholdVal;
1228
- if (typeof entropyMinLengthVal === 'number')
1229
- entOpts.entropyMinLength = entropyMinLengthVal;
1230
- if (Array.isArray(entropyWhitelistVal))
1231
- entOpts.entropyWhitelist = entropyWhitelistVal;
1232
- for (const [k, v] of Object.entries(resultDotenv)) {
1233
- maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1234
- logger.log(line);
1235
- });
1236
- }
1237
- }
1238
- // Load process.env.
1239
- if (loadProcess)
1240
- Object.assign(process.env, resultDotenv);
1241
- return resultDotenv;
1242
- };
1243
-
1244
- /**
1245
- * Deep interpolation utility for string leaves.
1246
- * - Expands string values using dotenv-style expansion against the provided envRef.
1247
- * - Preserves non-strings as-is.
1248
- * - Does not recurse into arrays (arrays are returned unchanged).
1249
- *
1250
- * Intended for:
1251
- * - Phase C option/config interpolation after composing ctx.dotenv.
1252
- * - Per-plugin config slice interpolation before afterResolve.
1253
- */
1254
- /** @internal */
1255
- const isPlainObject = (v) => v !== null &&
1256
- typeof v === 'object' &&
1257
- !Array.isArray(v) &&
1258
- Object.getPrototypeOf(v) === Object.prototype;
1259
- /**
1260
- * Deeply interpolate string leaves against envRef.
1261
- * Arrays are not recursed into; they are returned unchanged.
1262
- *
1263
- * @typeParam T - Shape of the input value.
1264
- * @param value - Input value (object/array/primitive).
1265
- * @param envRef - Reference environment for interpolation.
1266
- * @returns A new value with string leaves interpolated.
1267
- */
1268
- const interpolateDeep = (value, envRef) => {
1269
- // Strings: expand and return
1270
- if (typeof value === 'string') {
1271
- const out = dotenvExpand(value, envRef);
1272
- // dotenvExpand returns string | undefined; preserve original on undefined
1273
- return (out ?? value);
1274
- }
1275
- // Arrays: return as-is (no recursion)
1276
- if (Array.isArray(value)) {
1277
- return value;
1278
- }
1279
- // Plain objects: shallow clone and recurse into values
1280
- if (isPlainObject(value)) {
1281
- const src = value;
1282
- const out = {};
1283
- for (const [k, v] of Object.entries(src)) {
1284
- // Recurse for strings/objects; keep arrays as-is; preserve other scalars
1285
- if (typeof v === 'string')
1286
- out[k] = dotenvExpand(v, envRef) ?? v;
1287
- else if (Array.isArray(v))
1288
- out[k] = v;
1289
- else if (isPlainObject(v))
1290
- out[k] = interpolateDeep(v, envRef);
1291
- else
1292
- out[k] = v;
1293
- }
1294
- return out;
1295
- }
1296
- // Other primitives/types: return as-is
1297
- return value;
1298
- };
1299
-
1300
- /**
1301
- * Compute the dotenv context for the host (uses the config loader/overlay path).
1302
- * - Resolves and validates options strictly (host-only).
1303
- * - Applies file cascade, overlays, dynamics, and optional effects.
1304
- * - Merges and validates per-plugin config slices (when provided).
1305
- *
1306
- * @param customOptions - Partial options from the current invocation.
1307
- * @param plugins - Installed plugins (for config validation).
1308
- * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
1309
- const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1310
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1311
- const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1312
- // Always-on loader path
1313
- // 1) Base from files only (no dynamic, no programmatic vars)
1314
- const base = await getDotenv({
1315
- ...validated,
1316
- // Build a pure base without side effects or logging.
1317
- excludeDynamic: true,
1318
- vars: {},
1319
- log: false,
1320
- loadProcess: false,
1321
- outputPath: undefined,
1322
- });
1323
- // 2) Discover config sources and overlay
1324
- const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1325
- const dotenvOverlaid = overlayEnv({
1326
- base,
1327
- env: validated.env ?? validated.defaultEnv,
1328
- configs: sources,
1329
- ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1330
- });
1331
- // Helper to apply a dynamic map progressively.
1332
- const applyDynamic = (target, dynamic, env) => {
1333
- if (!dynamic)
1334
- return;
1335
- for (const key of Object.keys(dynamic)) {
1336
- const value = typeof dynamic[key] === 'function'
1337
- ? dynamic[key](target, env)
1338
- : dynamic[key];
1339
- Object.assign(target, { [key]: value });
1340
- }
1341
- };
1342
- // 3) Apply dynamics in order
1343
- const dotenv = { ...dotenvOverlaid };
1344
- applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1345
- applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1346
- applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1347
- applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1348
- // file dynamicPath (lowest)
1349
- if (validated.dynamicPath) {
1350
- const absDynamicPath = path.resolve(validated.dynamicPath);
1351
- try {
1352
- const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
1353
- applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
1354
- }
1355
- catch {
1356
- throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
1357
- }
1358
- }
1359
- // 4) Output/log/process merge
1360
- if (validated.outputPath) {
1361
- await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
1362
- const value = dotenv[key] ?? '';
1363
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1364
- }, ''), { encoding: 'utf-8' });
1365
- }
1366
- const logger = validated.logger ?? console;
1367
- if (validated.log)
1368
- logger.log(dotenv);
1369
- if (validated.loadProcess)
1370
- Object.assign(process.env, dotenv);
1371
- // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
1372
- const packagedPlugins = (sources.packaged &&
1373
- sources.packaged.plugins) ??
1374
- {};
1375
- const publicPlugins = (sources.project?.public &&
1376
- sources.project.public.plugins) ??
1377
- {};
1378
- const localPlugins = (sources.project?.local &&
1379
- sources.project.local.plugins) ??
1380
- {};
1381
- const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
1382
- for (const p of plugins) {
1383
- if (!p.id)
1384
- continue;
1385
- const slice = mergedPluginConfigs[p.id];
1386
- if (slice === undefined)
1387
- continue;
1388
- // Per-plugin interpolation just before validation/afterResolve:
1389
- // precedence: process.env wins over ctx.dotenv for slice defaults.
1390
- const envRef = {
1391
- ...dotenv,
1392
- ...process.env,
1393
- };
1394
- const interpolated = interpolateDeep(slice, envRef);
1395
- // Validate if a schema is provided; otherwise accept interpolated slice as-is.
1396
- if (p.configSchema) {
1397
- const parsed = p.configSchema.safeParse(interpolated);
1398
- if (!parsed.success) {
1399
- const msgs = parsed.error.issues
1400
- .map((i) => `${i.path.join('.')}: ${i.message}`)
1401
- .join('\n');
1402
- throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
1403
- }
1404
- mergedPluginConfigs[p.id] = parsed.data;
1405
- }
1406
- else {
1407
- mergedPluginConfigs[p.id] = interpolated;
1408
- }
1409
- }
1410
- return {
1411
- optionsResolved: validated,
1412
- dotenv: dotenv,
1413
- plugins: {},
1414
- pluginConfigs: mergedPluginConfigs,
1415
- };
1416
- };
1417
-
1418
- const HOST_META_URL = import.meta.url;
1419
- const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
1420
- const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
1421
- const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1422
- /**
1423
- * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
1424
- *
1425
- * Responsibilities:
1426
- * - Resolve options strictly and compute dotenv context (resolveAndLoad).
1427
- * - Expose a stable accessor for the current context (getCtx).
1428
- * - Provide a namespacing helper (ns).
1429
- * - Support composable plugins with parent → children install and afterResolve.
1430
- *
1431
- * NOTE: This host is additive and does not alter the legacy CLI.
1432
- */
1433
- class GetDotenvCli extends Command {
1434
- /** Registered top-level plugins (composition happens via .use()) */
1435
- _plugins = [];
1436
- /** One-time installation guard */
1437
- _installed = false;
1438
- /** Optional header line to prepend in help output */
1439
- [HELP_HEADER_SYMBOL];
1440
- constructor(alias = 'getdotenv') {
1441
- super(alias);
1442
- // Ensure subcommands that use passThroughOptions can be attached safely.
1443
- // Commander requires parent commands to enable positional options when a
1444
- // child uses passThroughOptions.
1445
- this.enablePositionalOptions();
1446
- // Configure grouped help: show only base options in default "Options";
1447
- // append App/Plugin sections after default help.
1448
- this.configureHelp({
1449
- visibleOptions: (cmd) => {
1450
- const all = cmd.options ??
1451
- [];
1452
- const base = all.filter((opt) => {
1453
- const group = opt.__group;
1454
- return group === 'base';
1455
- });
1456
- // Sort: short-aliased options first, then long-only; stable by flags.
1457
- const hasShort = (opt) => {
1458
- const flags = opt.flags ?? '';
1459
- // Matches "-x," or starting "-x " before any long
1460
- return /(^|\s|,)-[A-Za-z]/.test(flags);
1461
- };
1462
- const byFlags = (opt) => opt.flags ?? '';
1463
- base.sort((a, b) => {
1464
- const aS = hasShort(a) ? 1 : 0;
1465
- const bS = hasShort(b) ? 1 : 0;
1466
- return bS - aS || byFlags(a).localeCompare(byFlags(b));
1467
- });
1468
- return base;
1469
- },
1470
- });
1471
- this.addHelpText('beforeAll', () => {
1472
- const header = this[HELP_HEADER_SYMBOL];
1473
- return header && header.length > 0 ? `${header}\n\n` : '';
1474
- });
1475
- this.addHelpText('afterAll', (ctx) => this.#renderOptionGroups(ctx.command));
1476
- // Skeleton preSubcommand hook: produce a context if absent, without
1477
- // mutating process.env. The passOptions hook (when installed) will // compute the final context using merged CLI options; keeping
1478
- // loadProcess=false here avoids leaking dotenv values into the parent
1479
- // process env before subcommands execute.
1480
- this.hook('preSubcommand', async () => {
1481
- if (this.getCtx())
1482
- return;
1483
- await this.resolveAndLoad({ loadProcess: false });
1484
- });
1485
- }
1486
- /**
1487
- * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
1488
- */
1489
- async resolveAndLoad(customOptions = {}) {
1490
- // Resolve defaults, then validate strictly under the new host.
1491
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1492
- getDotenvOptionsSchemaResolved.parse(optionsResolved);
1493
- // Delegate the heavy lifting to the shared helper (guarded path supported).
1494
- const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
1495
- // Persist context on the instance for later access.
1496
- this[CTX_SYMBOL] =
1497
- ctx;
1498
- // Ensure plugins are installed exactly once, then run afterResolve.
1499
- await this.install();
1500
- await this._runAfterResolve(ctx);
1501
- return ctx;
1502
- }
1503
- /**
1504
- * Retrieve the current invocation context (if any).
1505
- */
1506
- getCtx() {
1507
- return this[CTX_SYMBOL];
1508
- }
1509
- /**
1510
- * Retrieve the merged root CLI options bag (if set by passOptions()).
1511
- * Downstream-safe: no generics required.
1512
- */
1513
- getOptions() {
1514
- return this[OPTS_SYMBOL];
1515
- }
1516
- /** Internal: set the merged root options bag for this run. */
1517
- _setOptionsBag(bag) {
1518
- this[OPTS_SYMBOL] = bag;
1519
- }
1520
- /** * Convenience helper to create a namespaced subcommand.
1521
- */
1522
- ns(name) {
1523
- return this.command(name);
1524
- }
1525
- /**
1526
- * Tag options added during the provided callback as 'app' for grouped help.
1527
- * Allows downstream apps to demarcate their root-level options.
1528
- */
1529
- tagAppOptions(fn) {
1530
- const root = this;
1531
- const originalAddOption = root.addOption.bind(root);
1532
- const originalOption = root.option.bind(root);
1533
- const tagLatest = (cmd, group) => {
1534
- const optsArr = cmd.options;
1535
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1536
- const last = optsArr[optsArr.length - 1];
1537
- last.__group = group;
1538
- }
1539
- };
1540
- root.addOption = function patchedAdd(opt) {
1541
- opt.__group = 'app';
1542
- return originalAddOption(opt);
1543
- };
1544
- root.option = function patchedOption(...args) {
1545
- const ret = originalOption(...args);
1546
- tagLatest(this, 'app');
1547
- return ret;
1548
- };
1549
- try {
1550
- return fn(root);
1551
- }
1552
- finally {
1553
- root.addOption = originalAddOption;
1554
- root.option = originalOption;
1555
- }
1556
- }
1557
- /**
1558
- * Branding helper: set CLI name/description/version and optional help header.
1559
- * If version is omitted and importMetaUrl is provided, attempts to read the
1560
- * nearest package.json version (best-effort; non-fatal on failure).
1561
- */
1562
- async brand(args) {
1563
- const { name, description, version, importMetaUrl, helpHeader } = args;
1564
- if (typeof name === 'string' && name.length > 0)
1565
- this.name(name);
1566
- if (typeof description === 'string')
1567
- this.description(description);
1568
- let v = version;
1569
- if (!v && importMetaUrl) {
1570
- try {
1571
- const fromUrl = fileURLToPath(importMetaUrl);
1572
- const pkgDir = await packageDirectory({ cwd: fromUrl });
1573
- if (pkgDir) {
1574
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1575
- const pkg = JSON.parse(txt);
1576
- if (pkg.version)
1577
- v = pkg.version;
1578
- }
1579
- }
1580
- catch {
1581
- // best-effort only
1582
- }
1583
- }
1584
- if (v)
1585
- this.version(v);
1586
- // Help header:
1587
- // - If caller provides helpHeader, use it.
1588
- // - Otherwise, when a version is known, default to "<name> v<version>".
1589
- if (typeof helpHeader === 'string') {
1590
- this[HELP_HEADER_SYMBOL] = helpHeader;
1591
- }
1592
- else if (v) {
1593
- // Use the current command name (possibly overridden by 'name' above).
1594
- const header = `${this.name()} v${v}`;
1595
- this[HELP_HEADER_SYMBOL] = header;
1596
- }
1597
- return this;
1598
- }
1599
- /**
1600
- * Register a plugin for installation (parent level).
1601
- * Installation occurs on first resolveAndLoad() (or explicit install()).
1602
- */
1603
- use(plugin) {
1604
- this._plugins.push(plugin);
1605
- // Immediately run setup so subcommands exist before parsing.
1606
- const setupOne = (p) => {
1607
- p.setup(this);
1608
- for (const child of p.children)
1609
- setupOne(child);
1610
- };
1611
- setupOne(plugin);
1612
- return this;
1613
- }
1614
- /**
1615
- * Install all registered plugins in parent → children (pre-order).
1616
- * Runs only once per CLI instance.
1617
- */
1618
- async install() {
1619
- // Setup is performed immediately in use(); here we only guard for afterResolve.
1620
- this._installed = true;
1621
- // Satisfy require-await without altering behavior.
1622
- await Promise.resolve();
1623
- }
626
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
1624
627
  /**
1625
- * Run afterResolve hooks for all plugins (parent → children).
628
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
629
+ *
630
+ * - 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`
631
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
632
+ * - Drops CLI-only keys that have no programmatic equivalent.
633
+ *
634
+ * @remarks
635
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
1626
636
  */
1627
- async _runAfterResolve(ctx) {
1628
- const run = async (p) => {
1629
- if (p.afterResolve)
1630
- await p.afterResolve(this, ctx);
1631
- for (const child of p.children)
1632
- await run(child);
1633
- };
1634
- for (const p of this._plugins)
1635
- await run(p);
1636
- }
1637
- // Render App/Plugin grouped options appended after default help.
1638
- #renderOptionGroups(cmd) {
1639
- const all = cmd.options ?? [];
1640
- const byGroup = new Map();
1641
- for (const o of all) {
1642
- const opt = o;
1643
- const g = opt.__group;
1644
- if (!g || g === 'base')
1645
- continue; // base handled by default help
1646
- const rows = byGroup.get(g) ?? [];
1647
- rows.push({
1648
- flags: opt.flags ?? '',
1649
- description: opt.description ?? '',
1650
- });
1651
- byGroup.set(g, rows);
1652
- }
1653
- if (byGroup.size === 0)
1654
- return '';
1655
- const renderRows = (title, rows) => {
1656
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1657
- // Sort within group: short-aliased flags first
1658
- rows.sort((a, b) => {
1659
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1660
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1661
- return bS - aS || a.flags.localeCompare(b.flags);
1662
- });
1663
- const lines = rows
1664
- .map((r) => {
1665
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1666
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1667
- })
1668
- .join('\n');
1669
- return `\n${title}:\n${lines}\n`;
1670
- };
1671
- let out = '';
1672
- // App options (if any)
1673
- const app = byGroup.get('app');
1674
- if (app && app.length > 0) {
1675
- out += renderRows('App options', app);
1676
- }
1677
- // Plugin groups sorted by id
1678
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1679
- pluginKeys.sort((a, b) => a.localeCompare(b));
1680
- for (const k of pluginKeys) {
1681
- const id = k.slice('plugin:'.length) || '(unknown)';
1682
- const rows = byGroup.get(k) ?? [];
1683
- if (rows.length > 0) {
1684
- out += renderRows(`Plugin options — ${id}`, rows);
1685
- }
1686
- }
1687
- return out;
637
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
638
+ // Create a shallow copy then delete optional CLI-only keys if present.
639
+ const restObj = { ...rest };
640
+ delete restObj.debug;
641
+ delete restObj.scripts;
642
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
643
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
644
+ let parsedVars;
645
+ if (typeof vars === 'string') {
646
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
647
+ ? RegExp(varsAssignorPattern)
648
+ : (varsAssignor ?? '=')));
649
+ parsedVars = Object.fromEntries(kvPairs);
1688
650
  }
1689
- }
1690
-
1691
- /**
1692
- * Validate a composed env against config-provided validation surfaces.
1693
- * Precedence for validation definitions:
1694
- * project.local -\> project.public -\> packaged
1695
- *
1696
- * Behavior:
1697
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
1698
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
1699
- * - Returns a flat list of issue strings; caller decides warn vs fail.
1700
- */
1701
- const validateEnvAgainstSources = (finalEnv, sources) => {
1702
- const pick = (getter) => {
1703
- const pl = sources.project?.local;
1704
- const pp = sources.project?.public;
1705
- const pk = sources.packaged;
1706
- return ((pl && getter(pl)) ||
1707
- (pp && getter(pp)) ||
1708
- (pk && getter(pk)) ||
1709
- undefined);
1710
- };
1711
- const schema = pick((cfg) => cfg['schema']);
1712
- if (schema &&
1713
- typeof schema.safeParse === 'function') {
1714
- try {
1715
- const parsed = schema.safeParse(finalEnv);
1716
- if (!parsed.success) {
1717
- // Try to render zod-style issues when available.
1718
- const err = parsed.error;
1719
- const issues = Array.isArray(err.issues) && err.issues.length > 0
1720
- ? err.issues.map((i) => {
1721
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
1722
- const msg = i.message ?? 'Invalid value';
1723
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
1724
- })
1725
- : ['[schema] validation failed'];
1726
- return issues;
1727
- }
1728
- return [];
1729
- }
1730
- catch {
1731
- // If schema invocation fails, surface a single diagnostic.
1732
- return [
1733
- '[schema] validation failed (unable to execute schema.safeParse)',
1734
- ];
1735
- }
651
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
652
+ // Keep only string or undefined values to match ProcessEnv.
653
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
654
+ parsedVars = Object.fromEntries(entries);
1736
655
  }
1737
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
1738
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
1739
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
1740
- if (missing.length > 0) {
1741
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
1742
- }
656
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
657
+ // expectations and the compat test assertions.
658
+ if (parsedVars) {
659
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
1743
660
  }
1744
- return [];
1745
- };
1746
-
1747
- /**
1748
- * Attach legacy root flags to a Commander program.
1749
- * Uses provided defaults to render help labels without coupling to generators.
1750
- */
1751
- const attachRootOptions = (program, defaults, opts) => {
1752
- // Install temporary wrappers to tag all options added here as "base".
1753
- const GROUP = 'base';
1754
- const tagLatest = (cmd, group) => {
1755
- const optsArr = cmd.options;
1756
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1757
- const last = optsArr[optsArr.length - 1];
1758
- last.__group = group;
1759
- }
1760
- };
1761
- const originalAddOption = program.addOption.bind(program);
1762
- const originalOption = program.option.bind(program);
1763
- program.addOption = function patchedAdd(opt) {
1764
- // Tag before adding, in case consumers inspect the Option directly.
1765
- opt.__group = GROUP;
1766
- const ret = originalAddOption(opt);
1767
- return ret;
1768
- };
1769
- program.option = function patchedOption(...args) {
1770
- const ret = originalOption(...args);
1771
- tagLatest(this, GROUP);
1772
- return ret;
661
+ // Tolerate paths as either a delimited string or string[]
662
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
663
+ // under the RootOptionsShape (which declares paths as string | undefined).
664
+ const pathsAny = paths;
665
+ const pathsOut = Array.isArray(pathsAny)
666
+ ? pathsAny.filter((p) => typeof p === 'string')
667
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
668
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
669
+ return {
670
+ ...restObj,
671
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
672
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
1773
673
  };
1774
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1775
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1776
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1777
- // Build initial chain.
1778
- let p = program
1779
- .enablePositionalOptions()
1780
- .passThroughOptions()
1781
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1782
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1783
- ['KEY1', 'VAL1'],
1784
- ['KEY2', 'VAL2'],
1785
- ]
1786
- .map((v) => v.join(va))
1787
- .join(vd)}`, dotenvExpandFromProcessEnv);
1788
- // Optional legacy root command flag (kept for generated CLI compatibility).
1789
- // Default is OFF; the generator opts in explicitly.
1790
- if (opts?.includeCommandOption === true) {
1791
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1792
- }
1793
- p = p
1794
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
1795
- .addOption(new Option('-s, --shell [string]', (() => {
1796
- let defaultLabel = '';
1797
- if (shell !== undefined) {
1798
- if (typeof shell === 'boolean') {
1799
- defaultLabel = ' (default OS shell)';
1800
- }
1801
- else if (typeof shell === 'string') {
1802
- // Safe string interpolation
1803
- defaultLabel = ` (default ${shell})`;
1804
- }
1805
- }
1806
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
1807
- })()).conflicts('shellOff'))
1808
- .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
1809
- .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
1810
- .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
1811
- .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1812
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1813
- ? ' (default)'
1814
- : ''}`).conflicts('excludeAllOff'))
1815
- .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
1816
- .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
1817
- .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
1818
- .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
1819
- .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
1820
- .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
1821
- .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
1822
- .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
1823
- .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
1824
- .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
1825
- .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
1826
- .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
1827
- .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
1828
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
1829
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
1830
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
1831
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
1832
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
1833
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
1834
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
1835
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
1836
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
1837
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
1838
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
1839
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
1840
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1841
- // Hidden scripts pipe-through (stringified)
1842
- .addOption(new Option('--scripts <string>')
1843
- .default(JSON.stringify(scripts))
1844
- .hideHelp());
1845
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1846
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1847
- // Validation: strict mode fails on env validation issues (warn by default).
1848
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1849
- // Entropy diagnostics (presentation-only)
1850
- p = p
1851
- .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
1852
- .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
1853
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
1854
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
1855
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
1856
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1857
- // Restore original methods to avoid tagging future additions outside base.
1858
- program.addOption = originalAddOption;
1859
- program.option = originalOption;
1860
- return p;
1861
- };
1862
-
1863
- /**
1864
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1865
- * - If the user explicitly enabled the flag, return true.
1866
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1867
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
1868
- *
1869
- * @param exclude - The "on" flag value as parsed by Commander.
1870
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1871
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1872
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1873
- *
1874
- * @example
1875
- * ```ts
1876
- * resolveExclusion(undefined, undefined, true); // => true
1877
- * ```
1878
- */
1879
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1880
- /**
1881
- * Resolve an optional flag with "--exclude-all" overrides.
1882
- * If excludeAll is set and the individual "...-off" is not, force true.
1883
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1884
- * Otherwise, adopt the default (true → set; false/undefined → unset).
1885
- *
1886
- * @param exclude - Individual include/exclude flag.
1887
- * @param excludeOff - Individual "...-off" flag.
1888
- * @param defaultValue - Default for the individual flag.
1889
- * @param excludeAll - Global "exclude-all" flag.
1890
- * @param excludeAllOff - Global "exclude-all-off" flag.
1891
- *
1892
- * @example
1893
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1894
- */
1895
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1896
- // Order of precedence:
1897
- // 1) Individual explicit "on" wins outright.
1898
- // 2) Individual explicit "off" wins over any global.
1899
- // 3) Global exclude-all forces true when not explicitly turned off.
1900
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1901
- // 5) Fall back to the default (true => set; false/undefined => unset).
1902
- (() => {
1903
- // Individual "on"
1904
- if (exclude === true)
1905
- return true;
1906
- // Individual "off"
1907
- if (excludeOff === true)
1908
- return undefined;
1909
- // Global "exclude-all" ON (unless explicitly turned off)
1910
- if (excludeAll === true)
1911
- return true;
1912
- // Global "exclude-all-off" (unless explicitly enabled)
1913
- if (excludeAllOff === true)
1914
- return undefined;
1915
- // Default
1916
- return defaultValue ? true : undefined;
1917
- })();
1918
- /**
1919
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1920
- * delete when undefined; assign when defined — without requiring an index signature on T.
1921
- *
1922
- * @typeParam T - Target object type.
1923
- * @param obj - The object to write to.
1924
- * @param key - The optional boolean property key of {@link T}.
1925
- * @param value - The value to set or `undefined` to unset.
1926
- *
1927
- * @remarks
1928
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1929
- */
1930
- const setOptionalFlag = (obj, key, value) => {
1931
- const target = obj;
1932
- const k = key;
1933
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1934
- if (value === undefined)
1935
- delete target[k];
1936
- else
1937
- target[k] = value;
1938
- };
1939
-
1940
- /**
1941
- * Merge and normalize raw Commander options (current + parent + defaults)
1942
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1943
- * avoid cross-layer coupling; callers may cast as needed.
1944
- */
1945
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1946
- const parent = typeof parentJson === 'string' && parentJson.length > 0
1947
- ? JSON.parse(parentJson)
1948
- : undefined;
1949
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1950
- const current = { ...rest };
1951
- if (typeof scripts === 'string') {
1952
- try {
1953
- current.scripts = JSON.parse(scripts);
1954
- }
1955
- catch {
1956
- // ignore parse errors; leave scripts undefined
1957
- }
1958
- }
1959
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1960
- const d = defaults;
1961
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1962
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1963
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1964
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1965
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1966
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1967
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1968
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1969
- // warnEntropy (tri-state)
1970
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1971
- // Normalize shell for predictability: explicit default shell per OS.
1972
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1973
- let resolvedShell = merged.shell;
1974
- if (shellOff)
1975
- resolvedShell = false;
1976
- else if (resolvedShell === true || resolvedShell === undefined) {
1977
- resolvedShell = defaultShell;
1978
- }
1979
- else if (typeof resolvedShell !== 'string' &&
1980
- typeof defaults.shell === 'string') {
1981
- resolvedShell = defaults.shell;
1982
- }
1983
- merged.shell = resolvedShell;
1984
- const cmd = typeof command === 'string' ? command : undefined;
1985
- return cmd !== undefined ? { merged, command: cmd } : { merged };
1986
- };
1987
-
1988
- GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1989
- const d = (defaults ?? baseRootOptionDefaults);
1990
- attachRootOptions(this, d, opts);
1991
- return this;
1992
- };
1993
- GetDotenvCli.prototype.passOptions = function (defaults) {
1994
- const d = (defaults ?? baseRootOptionDefaults);
1995
- this.hook('preSubcommand', async (thisCommand) => {
1996
- const raw = thisCommand.opts();
1997
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1998
- // Persist merged options for nested invocations (batch exec).
1999
- thisCommand.getDotenvCliOptions =
2000
- merged;
2001
- // Also store on the host for downstream ergonomic accessors.
2002
- this._setOptionsBag(merged);
2003
- // Build service options and compute context (always-on config loader path).
2004
- const serviceOptions = getDotenvCliOptions2Options(merged);
2005
- await this.resolveAndLoad(serviceOptions);
2006
- // Global validation: once after Phase C using config sources.
2007
- try {
2008
- const ctx = this.getCtx();
2009
- const dotenv = (ctx?.dotenv ?? {});
2010
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
2011
- const issues = validateEnvAgainstSources(dotenv, sources);
2012
- if (Array.isArray(issues) && issues.length > 0) {
2013
- const logger = (merged.logger ??
2014
- console);
2015
- const emit = logger.error ?? logger.log;
2016
- issues.forEach((m) => {
2017
- emit(m);
2018
- });
2019
- if (merged.strict) {
2020
- // Deterministic failure under strict mode
2021
- process.exit(1);
2022
- }
2023
- }
2024
- }
2025
- catch {
2026
- // Be tolerant: validation errors reported above; unexpected failures here
2027
- // should not crash non-strict flows.
2028
- }
2029
- });
2030
- // Also handle root-level flows (no subcommand) so option-aliases can run
2031
- // with the same merged options and context without duplicating logic.
2032
- this.hook('preAction', async (thisCommand) => {
2033
- const raw = thisCommand.opts();
2034
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2035
- thisCommand.getDotenvCliOptions =
2036
- merged;
2037
- this._setOptionsBag(merged);
2038
- // Avoid duplicate heavy work if a context is already present.
2039
- if (!this.getCtx()) {
2040
- const serviceOptions = getDotenvCliOptions2Options(merged);
2041
- await this.resolveAndLoad(serviceOptions);
2042
- try {
2043
- const ctx = this.getCtx();
2044
- const dotenv = (ctx?.dotenv ?? {});
2045
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
2046
- const issues = validateEnvAgainstSources(dotenv, sources);
2047
- if (Array.isArray(issues) && issues.length > 0) {
2048
- const logger = (merged
2049
- .logger ?? console);
2050
- const emit = logger.error ?? logger.log;
2051
- issues.forEach((m) => {
2052
- emit(m);
2053
- });
2054
- if (merged.strict) {
2055
- process.exit(1);
2056
- }
2057
- }
2058
- }
2059
- catch {
2060
- // Tolerate validation side-effects in non-strict mode
2061
- }
2062
- }
2063
- });
2064
- return this;
2065
674
  };
2066
675
 
2067
676
  const dbg = (...args) => {
@@ -2360,7 +969,7 @@ const cmdPlugin = (options = {}) => definePlugin({
2360
969
  const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
2361
970
  const cmd = new Command()
2362
971
  .name('cmd')
2363
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
972
+ .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
2364
973
  .configureHelp({ showGlobalOptions: true })
2365
974
  .enablePositionalOptions()
2366
975
  .passThroughOptions()