@karmaniverous/get-dotenv 6.2.3 → 6.3.0

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