@karmaniverous/get-dotenv 6.2.2 → 6.2.4

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 (89) hide show
  1. package/dist/chunks/AwsRestJsonProtocol-Bq1HE-Ln.mjs +932 -0
  2. package/dist/chunks/createCli-BY6_cfZr.mjs +439 -0
  3. package/dist/chunks/externalDataInterceptor-CbsdEYa-.mjs +19 -0
  4. package/dist/chunks/getSSOTokenFromFile-hUSpR7Wf.mjs +22 -0
  5. package/dist/chunks/helpConfig-CGejgwWW.mjs +12 -0
  6. package/dist/chunks/index-B5JKTBOL.mjs +443 -0
  7. package/dist/chunks/index-BEJFiHMX.mjs +522 -0
  8. package/dist/chunks/index-BPYF6K_G.mjs +82 -0
  9. package/dist/chunks/index-Bc3h0a95.mjs +374 -0
  10. package/dist/chunks/index-BpCF5UKx.mjs +272 -0
  11. package/dist/chunks/index-C_wqbTwI.mjs +187 -0
  12. package/dist/chunks/index-CeCufHlm.mjs +9374 -0
  13. package/dist/chunks/index-Cu7rdyqN.mjs +102 -0
  14. package/dist/chunks/index-DWAtHEA-.mjs +379 -0
  15. package/dist/chunks/index-Dp1Ip6Ra.mjs +354 -0
  16. package/dist/chunks/index-DyU5pKKi.mjs +24 -0
  17. package/dist/chunks/index-c7zKtEuy.mjs +578 -0
  18. package/dist/chunks/index-cIunyiUQ.mjs +702 -0
  19. package/dist/chunks/invoke-DuRPU1oC.mjs +60 -0
  20. package/dist/chunks/loadModuleDefault-Dj8B3Stt.mjs +123 -0
  21. package/dist/chunks/loadSso-w1eTVg0O.mjs +412 -0
  22. package/dist/chunks/loader-DnhPeGfq.mjs +346 -0
  23. package/dist/chunks/overlayEnv-Bs2kVayG.mjs +234 -0
  24. package/dist/chunks/package-boo9EyYs.mjs +5 -0
  25. package/dist/chunks/parseKnownFiles-B9cDK21V.mjs +23 -0
  26. package/dist/chunks/readMergedOptions-Nt0TR7dX.mjs +1626 -0
  27. package/dist/chunks/resolveCliOptions-TFRzhB2c.mjs +138 -0
  28. package/dist/chunks/sdk-stream-mixin-BZoJ5jy9.mjs +167 -0
  29. package/dist/chunks/spawnEnv-CN8a7cNR.mjs +306 -0
  30. package/dist/chunks/types-DJ-BGABd.mjs +59 -0
  31. package/dist/chunks/validate-CDl0rE6k.mjs +61 -0
  32. package/dist/cli.mjs +39 -19307
  33. package/dist/cliHost.mjs +20 -2800
  34. package/dist/config.mjs +10 -509
  35. package/dist/env-overlay.mjs +6 -337
  36. package/dist/getdotenv.cli.mjs +39 -19305
  37. package/dist/index.mjs +39 -19396
  38. package/dist/plugins-aws.d.ts +1 -4
  39. package/dist/plugins-aws.mjs +65 -2568
  40. package/dist/plugins-batch.mjs +16 -2573
  41. package/dist/plugins-cmd.mjs +19 -3094
  42. package/dist/plugins-init.d.ts +8 -0
  43. package/dist/plugins-init.mjs +85 -2297
  44. package/dist/plugins.mjs +36 -18817
  45. package/package.json +1 -2
  46. package/dist/templates/cli/index.ts +0 -25
  47. package/dist/templates/cli/plugins/hello/defaultAction.ts +0 -27
  48. package/dist/templates/cli/plugins/hello/index.ts +0 -26
  49. package/dist/templates/cli/plugins/hello/options.ts +0 -31
  50. package/dist/templates/cli/plugins/hello/strangerAction.ts +0 -20
  51. package/dist/templates/cli/plugins/hello/types.ts +0 -13
  52. package/dist/templates/config/js/getdotenv.config.js +0 -20
  53. package/dist/templates/config/json/local/getdotenv.config.local.json +0 -7
  54. package/dist/templates/config/json/public/getdotenv.config.json +0 -9
  55. package/dist/templates/config/public/getdotenv.config.json +0 -8
  56. package/dist/templates/config/ts/getdotenv.config.ts +0 -28
  57. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +0 -7
  58. package/dist/templates/config/yaml/public/getdotenv.config.yaml +0 -7
  59. package/dist/templates/defaultAction.ts +0 -27
  60. package/dist/templates/getdotenv.config.js +0 -20
  61. package/dist/templates/getdotenv.config.json +0 -9
  62. package/dist/templates/getdotenv.config.local.json +0 -7
  63. package/dist/templates/getdotenv.config.local.yaml +0 -7
  64. package/dist/templates/getdotenv.config.ts +0 -28
  65. package/dist/templates/getdotenv.config.yaml +0 -7
  66. package/dist/templates/hello/defaultAction.ts +0 -27
  67. package/dist/templates/hello/index.ts +0 -26
  68. package/dist/templates/hello/options.ts +0 -31
  69. package/dist/templates/hello/strangerAction.ts +0 -20
  70. package/dist/templates/hello/types.ts +0 -13
  71. package/dist/templates/index.ts +0 -26
  72. package/dist/templates/js/getdotenv.config.js +0 -20
  73. package/dist/templates/json/local/getdotenv.config.local.json +0 -7
  74. package/dist/templates/json/public/getdotenv.config.json +0 -9
  75. package/dist/templates/local/getdotenv.config.local.json +0 -7
  76. package/dist/templates/local/getdotenv.config.local.yaml +0 -7
  77. package/dist/templates/options.ts +0 -31
  78. package/dist/templates/plugins/hello/defaultAction.ts +0 -27
  79. package/dist/templates/plugins/hello/index.ts +0 -26
  80. package/dist/templates/plugins/hello/options.ts +0 -31
  81. package/dist/templates/plugins/hello/strangerAction.ts +0 -20
  82. package/dist/templates/plugins/hello/types.ts +0 -13
  83. package/dist/templates/public/getdotenv.config.json +0 -9
  84. package/dist/templates/public/getdotenv.config.yaml +0 -7
  85. package/dist/templates/strangerAction.ts +0 -20
  86. package/dist/templates/ts/getdotenv.config.ts +0 -28
  87. package/dist/templates/types.ts +0 -13
  88. package/dist/templates/yaml/local/getdotenv.config.local.yaml +0 -7
  89. package/dist/templates/yaml/public/getdotenv.config.yaml +0 -7
@@ -1,2542 +1,19 @@
1
+ import { r as readMergedOptions, d as definePlugin } from './chunks/readMergedOptions-Nt0TR7dX.mjs';
2
+ import 'execa';
3
+ import 'fs-extra';
4
+ import 'crypto';
5
+ import 'path';
6
+ import 'url';
7
+ import '@commander-js/extra-typings';
8
+ import 'nanoid';
9
+ import 'dotenv';
10
+ import './chunks/loader-DnhPeGfq.mjs';
11
+ import 'package-directory';
12
+ import 'yaml';
1
13
  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
- for (let i = 0; i < command.length; i++) {
604
- const c = command.charAt(i);
605
- if (quote) {
606
- if (c === quote) {
607
- // Support doubled quotes inside a quoted segment:
608
- // default: "" -> " and '' -> ' (Windows/PowerShell style)
609
- // preserve: keep as "" to allow empty string literals in Node -e payloads
610
- const next = command.charAt(i + 1);
611
- if (next === quote) {
612
- {
613
- // Collapse to a single literal quote
614
- cur += quote;
615
- i += 1; // skip the second quote
616
- }
617
- }
618
- else {
619
- // end of quoted segment
620
- quote = null;
621
- }
622
- }
623
- else {
624
- cur += c;
625
- }
626
- }
627
- else {
628
- if (c === '"' || c === "'") {
629
- quote = c;
630
- }
631
- else if (/\s/.test(c)) {
632
- if (cur) {
633
- out.push(cur);
634
- cur = '';
635
- }
636
- }
637
- else {
638
- cur += c;
639
- }
640
- }
641
- }
642
- if (cur)
643
- out.push(cur);
644
- return out;
645
- };
646
-
647
- /**
648
- * @packageDocumentation
649
- * Configuration discovery and loading for get‑dotenv. Discovers config files
650
- * in the packaged root and project root, loads JSON/YAML/JS/TS documents, and
651
- * validates them against Zod schemas.
652
- */
653
- // Discovery candidates (first match wins per scope/privacy).
654
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
655
- const PUBLIC_FILENAMES = [
656
- 'getdotenv.config.json',
657
- 'getdotenv.config.yaml',
658
- 'getdotenv.config.yml',
659
- 'getdotenv.config.js',
660
- 'getdotenv.config.mjs',
661
- 'getdotenv.config.cjs',
662
- 'getdotenv.config.ts',
663
- 'getdotenv.config.mts',
664
- 'getdotenv.config.cts',
665
- ];
666
- const LOCAL_FILENAMES = [
667
- 'getdotenv.config.local.json',
668
- 'getdotenv.config.local.yaml',
669
- 'getdotenv.config.local.yml',
670
- 'getdotenv.config.local.js',
671
- 'getdotenv.config.local.mjs',
672
- 'getdotenv.config.local.cjs',
673
- 'getdotenv.config.local.ts',
674
- 'getdotenv.config.local.mts',
675
- 'getdotenv.config.local.cts',
676
- ];
677
- const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
678
- const isJson = (p) => extname(p).toLowerCase() === '.json';
679
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
680
- /**
681
- * Discover JSON/YAML config files in the packaged root and project root.
682
- * Order: packaged public → project public → project local. */
683
- const discoverConfigFiles = async (importMetaUrl) => {
684
- const files = [];
685
- // Packaged root via importMetaUrl (optional)
686
- if (importMetaUrl) {
687
- const fromUrl = fileURLToPath(importMetaUrl);
688
- const packagedRoot = await packageDirectory({ cwd: fromUrl });
689
- if (packagedRoot) {
690
- for (const name of PUBLIC_FILENAMES) {
691
- const p = join(packagedRoot, name);
692
- if (await fs.pathExists(p)) {
693
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
694
- break; // only one public file expected per scope
695
- }
696
- }
697
- // By policy, packaged .local is not expected; skip even if present.
698
- }
699
- }
700
- // Project root (from current working directory)
701
- const projectRoot = await packageDirectory();
702
- if (projectRoot) {
703
- for (const name of PUBLIC_FILENAMES) {
704
- const p = join(projectRoot, name);
705
- if (await fs.pathExists(p)) {
706
- files.push({ path: p, privacy: 'public', scope: 'project' });
707
- break;
708
- }
709
- }
710
- for (const name of LOCAL_FILENAMES) {
711
- const p = join(projectRoot, name);
712
- if (await fs.pathExists(p)) {
713
- files.push({ path: p, privacy: 'local', scope: 'project' });
714
- break;
715
- }
716
- }
717
- }
718
- return files;
719
- };
720
- /**
721
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
722
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
723
- *
724
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
725
- * For JS/TS: default export is loaded; "dynamic" is allowed.
726
- */
727
- const loadConfigFile = async (filePath) => {
728
- let raw = {};
729
- try {
730
- const abs = path.resolve(filePath);
731
- if (isJsOrTs(abs)) {
732
- // JS/TS support: load default export via shared robust pipeline.
733
- const mod = await loadModuleDefault(abs, 'getdotenv-config');
734
- raw = mod ?? {};
735
- }
736
- else {
737
- const txt = await fs.readFile(abs, 'utf-8');
738
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
739
- }
740
- }
741
- catch (err) {
742
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
743
- }
744
- // Validate RAW
745
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
746
- if (!parsed.success) {
747
- const msgs = parsed.error.issues
748
- .map((i) => `${i.path.join('.')}: ${i.message}`)
749
- .join('\n');
750
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
751
- }
752
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
753
- if (!isJsOrTs(filePath) &&
754
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
755
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
756
- `Use JS/TS config for "dynamic" or "schema".`);
757
- }
758
- return getDotenvConfigSchemaResolved.parse(parsed.data);
759
- };
760
- /**
761
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
762
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
763
- */
764
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
765
- const discovered = await discoverConfigFiles(importMetaUrl);
766
- const result = {};
767
- for (const f of discovered) {
768
- const cfg = await loadConfigFile(f.path);
769
- if (f.scope === 'packaged') {
770
- // packaged public only
771
- result.packaged = cfg;
772
- }
773
- else {
774
- result.project ??= {};
775
- if (f.privacy === 'public')
776
- result.project.public = cfg;
777
- else
778
- result.project.local = cfg;
779
- }
780
- }
781
- return result;
782
- };
783
-
784
- /** src/env/dynamic.ts
785
- * Helpers for applying and loading dynamic variables (JS/TS).
786
- *
787
- * Requirements addressed:
788
- * - Single service to apply a dynamic map progressively.
789
- * - Single service to load a JS/TS dynamic module with robust fallbacks (util/loadModuleDefault).
790
- * - Unify error messaging so callers show consistent guidance.
791
- */
792
- /**
793
- * Apply a dynamic map to the target progressively.
794
- * - Functions receive (target, env) and may return string | undefined.
795
- * - Literals are assigned directly (including undefined).
796
- *
797
- * @param target - Mutable target environment to assign into.
798
- * @param map - Dynamic map to apply (functions and/or literal values).
799
- * @param env - Selected environment name (if any) passed through to dynamic functions.
800
- * @returns Nothing.
801
- */
802
- function applyDynamicMap(target, map, env) {
803
- if (!map)
804
- return;
805
- for (const key of Object.keys(map)) {
806
- const val = typeof map[key] === 'function'
807
- ? map[key](target, env)
808
- : map[key];
809
- Object.assign(target, { [key]: val });
810
- }
811
- }
812
- /**
813
- * Load a default-export dynamic map from a JS/TS file and apply it.
814
- * Uses util/loadModuleDefault for robust TS handling (direct import, esbuild,
815
- * typescript.transpile fallback).
816
- *
817
- * Error behavior:
818
- * - On failure to load/compile/evaluate the module, throws a unified message:
819
- * "Unable to load dynamic TypeScript file: <absPath>. Install 'esbuild'..."
820
- *
821
- * @param target - Mutable target environment to assign into.
822
- * @param absPath - Absolute path to the dynamic module file.
823
- * @param env - Selected environment name (if any).
824
- * @param cacheDirName - Cache subdirectory under `.tsbuild/` for compiled artifacts.
825
- * @returns A `Promise\<void\>` which resolves after the module (if present) has been applied.
826
- */
827
- async function loadAndApplyDynamic(target, absPath, env, cacheDirName) {
828
- if (!(await fs.exists(absPath)))
829
- return;
830
- let dyn;
831
- try {
832
- dyn = await loadModuleDefault(absPath, cacheDirName);
833
- }
834
- catch {
835
- // Preserve legacy/clear guidance used by tests and docs.
836
- throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
837
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
838
- }
839
- applyDynamicMap(target, dyn, env);
840
- }
841
-
842
- const applyKv = (current, kv) => {
843
- if (!kv || Object.keys(kv).length === 0)
844
- return current;
845
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
846
- return { ...current, ...expanded };
847
- };
848
- const applyConfigSlice = (current, cfg, env) => {
849
- if (!cfg)
850
- return current;
851
- // kind axis: global then env (env overrides global)
852
- const afterGlobal = applyKv(current, cfg.vars);
853
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
854
- return applyKv(afterGlobal, envKv);
855
- };
856
- function overlayEnv(args) {
857
- const { base, env, configs } = args;
858
- let current = { ...base };
859
- // Source: packaged (public -> local)
860
- current = applyConfigSlice(current, configs.packaged, env);
861
- // Packaged "local" is not expected by policy; if present, honor it.
862
- // We do not have a separate object for packaged.local in sources, keep as-is.
863
- // Source: project (public -> local)
864
- current = applyConfigSlice(current, configs.project?.public, env);
865
- current = applyConfigSlice(current, configs.project?.local, env);
866
- // Programmatic explicit vars (top of static tier)
867
- if ('programmaticVars' in args) {
868
- const toApply = Object.fromEntries(Object.entries(args.programmaticVars).filter(([_k, v]) => typeof v === 'string'));
869
- current = applyKv(current, toApply);
870
- }
871
- return current;
872
- }
873
-
874
- /** src/diagnostics/entropy.ts
875
- * Entropy diagnostics (presentation-only).
876
- * - Gated by min length and printable ASCII.
877
- * - Warn once per key per run when bits/char \>= threshold.
878
- * - Supports whitelist patterns to suppress known-noise keys.
879
- */
880
- const warned = new Set();
881
- const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
882
- const compile$1 = (patterns) => (patterns ?? []).map((p) => (typeof p === 'string' ? new RegExp(p, 'i') : p));
883
- const whitelisted = (key, regs) => regs.some((re) => re.test(key));
884
- const shannonBitsPerChar = (s) => {
885
- const freq = new Map();
886
- for (const ch of s)
887
- freq.set(ch, (freq.get(ch) ?? 0) + 1);
888
- const n = s.length;
889
- let h = 0;
890
- for (const c of freq.values()) {
891
- const p = c / n;
892
- h -= p * Math.log2(p);
893
- }
894
- return h;
895
- };
896
- /**
897
- * Maybe emit a one-line entropy warning for a key.
898
- * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
899
- */
900
- const maybeWarnEntropy = (key, value, origin, opts, emit) => {
901
- if (!opts || opts.warnEntropy === false)
902
- return;
903
- if (warned.has(key))
904
- return;
905
- const v = value ?? '';
906
- const minLen = Math.max(0, opts.entropyMinLength ?? 16);
907
- const threshold = opts.entropyThreshold ?? 3.8;
908
- if (v.length < minLen)
909
- return;
910
- if (!isPrintableAscii(v))
911
- return;
912
- const wl = compile$1(opts.entropyWhitelist);
913
- if (whitelisted(key, wl))
914
- return;
915
- const bpc = shannonBitsPerChar(v);
916
- if (bpc >= threshold) {
917
- warned.add(key);
918
- emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
919
- }
920
- };
921
-
922
- const DEFAULT_PATTERNS = [
923
- '\\bsecret\\b',
924
- '\\btoken\\b',
925
- '\\bpass(word)?\\b',
926
- '\\bapi[_-]?key\\b',
927
- '\\bkey\\b',
928
- ];
929
- const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => typeof p === 'string' ? new RegExp(p, 'i') : p);
930
- const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
931
- const MASK = '[redacted]';
932
- /**
933
- * Produce a shallow redacted copy of an env-like object for display.
934
- */
935
- const redactObject = (obj, opts) => {
936
- if (!opts?.redact)
937
- return { ...obj };
938
- const regs = compile(opts.redactPatterns);
939
- const out = {};
940
- for (const [k, v] of Object.entries(obj)) {
941
- out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
942
- }
943
- return out;
944
- };
945
-
946
- /**
947
- * Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
948
- * Used as the bottom layer for CLI option resolution.
949
- */
950
- const baseScripts = {
951
- 'git-status': {
952
- cmd: 'git branch --show-current && git status -s -u',
953
- shell: true,
954
- },
955
- };
956
- /**
957
- * Default values for root CLI options used by the host and helpers as the baseline layer during option resolution.
958
- *
959
- * These defaults correspond to the “stringly” root surface (see `RootOptionsShape`) and are merged by precedence with:
960
- * - create-time overrides
961
- * - any discovered configuration `rootOptionDefaults`
962
- * - and finally CLI flags at runtime
963
- *
964
- * @public
965
- */
966
- const baseRootOptionDefaults = {
967
- dotenvToken: '.env',
968
- loadProcess: true,
969
- logger: console,
970
- // Diagnostics defaults
971
- warnEntropy: true,
972
- entropyThreshold: 3.8,
973
- entropyMinLength: 16,
974
- entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
975
- paths: './',
976
- pathsDelimiter: ' ',
977
- privateToken: 'local',
978
- scripts: baseScripts,
979
- shell: true,
980
- vars: '',
981
- varsAssignor: '=',
982
- varsDelimiter: ' ',
983
- // tri-state flags default to unset unless explicitly provided
984
- // (debug/log/exclude* resolved via flag utils)
985
- };
986
-
987
- /**
988
- * Converts programmatic CLI options to `getDotenv` options.
989
- *
990
- * Accepts "stringly" CLI inputs for vars/paths and normalizes them into
991
- * the programmatic shape. Preserves exactOptionalPropertyTypes semantics by
992
- * omitting keys when undefined.
993
- */
994
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern,
995
- // drop CLI-only keys from the pass-through bag
996
- debug: _debug, scripts: _scripts, ...rest }) => {
997
- // Split helper for delimited strings or regex patterns
998
- const splitBy = (value, delim, pattern) => {
999
- if (!value)
1000
- return [];
1001
- if (pattern)
1002
- return value.split(RegExp(pattern));
1003
- if (typeof delim === 'string')
1004
- return value.split(delim);
1005
- return value.split(' ');
1006
- };
1007
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
1008
- let parsedVars;
1009
- if (typeof vars === 'string') {
1010
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern)
1011
- .map((v) => v.split(varsAssignorPattern
1012
- ? RegExp(varsAssignorPattern)
1013
- : (varsAssignor ?? '=')))
1014
- .filter(([k]) => typeof k === 'string' && k.length > 0);
1015
- parsedVars = Object.fromEntries(kvPairs);
1016
- }
1017
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
1018
- // Accept provided object map of string | undefined; drop undefined values
1019
- // in the normalization step below to produce a ProcessEnv-compatible bag.
1020
- parsedVars = Object.fromEntries(Object.entries(vars));
1021
- }
1022
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
1023
- // expectations and the compat test assertions.
1024
- if (parsedVars) {
1025
- parsedVars = omitUndefinedRecord(parsedVars);
1026
- }
1027
- // Tolerate paths as either a delimited string or string[]
1028
- const pathsOut = Array.isArray(paths)
1029
- ? paths.filter((p) => typeof p === 'string')
1030
- : splitBy(paths, pathsDelimiter, pathsDelimiterPattern);
1031
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
1032
- return {
1033
- // Ensure the required logger property is present. The base CLI defaults
1034
- // specify console as the logger; callers can override upstream if desired.
1035
- logger: console,
1036
- ...rest,
1037
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
1038
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
1039
- };
1040
- };
1041
- /**
1042
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
1043
- *
1044
- * 1. Base defaults derived from the CLI generator defaults
1045
- * ({@link baseGetDotenvCliOptions}).
1046
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
1047
- * package root (if present).
1048
- * 3. The provided customOptions.
1049
- *
1050
- * The result preserves explicit empty values and drops only `undefined`.
1051
- */
1052
- const resolveGetDotenvOptions = (customOptions) => {
1053
- // Programmatic callers use neutral defaults only. Do not read local packaged
1054
- // getdotenv.config.json here; the host path applies packaged/project configs
1055
- // via the dedicated loader/overlay pipeline.
1056
- const mergedDefaults = baseRootOptionDefaults;
1057
- const defaultsFromCli = getDotenvCliOptions2Options(mergedDefaults);
1058
- const result = defaultsDeep(defaultsFromCli, customOptions);
1059
- return Promise.resolve({
1060
- ...result, // Keep explicit empty strings/zeros; drop only undefined
1061
- vars: omitUndefinedRecord(result.vars ?? {}),
1062
- });
1063
- };
1064
-
1065
- /**
1066
- * Asynchronously read a dotenv file & parse it into an object.
1067
- *
1068
- * @param path - Path to dotenv file.
1069
- * @returns The parsed dotenv object.
1070
- */
1071
- const readDotenv = async (path) => {
1072
- try {
1073
- return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
1074
- }
1075
- catch {
1076
- return {};
1077
- }
1078
- };
1079
-
1080
- async function getDotenv(options = {}) {
1081
- // Apply defaults.
1082
- 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);
1083
- // Read .env files.
1084
- const loaded = paths.length
1085
- ? await paths.reduce(async (e, p) => {
1086
- const publicGlobal = excludePublic || excludeGlobal
1087
- ? Promise.resolve({})
1088
- : readDotenv(path.resolve(p, dotenvToken));
1089
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1090
- ? Promise.resolve({})
1091
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1092
- const privateGlobal = excludePrivate || excludeGlobal
1093
- ? Promise.resolve({})
1094
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1095
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1096
- ? Promise.resolve({})
1097
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1098
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1099
- e,
1100
- publicGlobal,
1101
- publicEnv,
1102
- privateGlobal,
1103
- privateEnv,
1104
- ]);
1105
- return {
1106
- ...eResolved,
1107
- ...publicGlobalResolved,
1108
- ...publicEnvResolved,
1109
- ...privateGlobalResolved,
1110
- ...privateEnvResolved,
1111
- };
1112
- }, Promise.resolve({}))
1113
- : {};
1114
- const outputKey = nanoid();
1115
- const dotenv = dotenvExpandAll({
1116
- ...loaded,
1117
- ...vars,
1118
- ...(outputPath ? { [outputKey]: outputPath } : {}),
1119
- }, { progressive: true });
1120
- // Process dynamic variables. Programmatic option takes precedence over path.
1121
- if (!excludeDynamic) {
1122
- let dynamic = undefined;
1123
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1124
- dynamic = options.dynamic;
1125
- }
1126
- else if (dynamicPath) {
1127
- const absDynamicPath = path.resolve(dynamicPath);
1128
- await loadAndApplyDynamic(dotenv, absDynamicPath, env ?? defaultEnv, 'getdotenv-dynamic');
1129
- }
1130
- if (dynamic) {
1131
- try {
1132
- applyDynamicMap(dotenv, dynamic, env ?? defaultEnv);
1133
- }
1134
- catch {
1135
- throw new Error(`Unable to evaluate dynamic variables.`);
1136
- }
1137
- }
1138
- }
1139
- // Write output file.
1140
- let resultDotenv = dotenv;
1141
- if (outputPath) {
1142
- const outputPathResolved = dotenv[outputKey];
1143
- if (!outputPathResolved)
1144
- throw new Error('Output path not found.');
1145
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1146
- await writeDotenvFile(outputPathResolved, dotenvForOutput);
1147
- resultDotenv = dotenvForOutput;
1148
- }
1149
- // Log result.
1150
- if (log) {
1151
- const redactFlag = options.redact ?? false;
1152
- const redactPatterns = options.redactPatterns ?? undefined;
1153
- const redOpts = {};
1154
- if (redactFlag)
1155
- redOpts.redact = true;
1156
- if (redactFlag && Array.isArray(redactPatterns))
1157
- redOpts.redactPatterns = redactPatterns;
1158
- const bag = redactFlag
1159
- ? redactObject(resultDotenv, redOpts)
1160
- : { ...resultDotenv };
1161
- logger.log(bag);
1162
- // Entropy warnings: once-per-key-per-run (presentation only)
1163
- const warnEntropyVal = options.warnEntropy ?? true;
1164
- const entropyThresholdVal = options
1165
- .entropyThreshold;
1166
- const entropyMinLengthVal = options
1167
- .entropyMinLength;
1168
- const entropyWhitelistVal = options.entropyWhitelist;
1169
- const entOpts = {};
1170
- if (typeof warnEntropyVal === 'boolean')
1171
- entOpts.warnEntropy = warnEntropyVal;
1172
- if (typeof entropyThresholdVal === 'number')
1173
- entOpts.entropyThreshold = entropyThresholdVal;
1174
- if (typeof entropyMinLengthVal === 'number')
1175
- entOpts.entropyMinLength = entropyMinLengthVal;
1176
- if (Array.isArray(entropyWhitelistVal))
1177
- entOpts.entropyWhitelist = entropyWhitelistVal;
1178
- for (const [k, v] of Object.entries(resultDotenv)) {
1179
- maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1180
- logger.log(line);
1181
- });
1182
- }
1183
- }
1184
- // Load process.env.
1185
- if (loadProcess)
1186
- Object.assign(process.env, resultDotenv);
1187
- return resultDotenv;
1188
- }
1189
-
1190
- /**
1191
- * Compute the realized path for a command mount (leaf-up to root).
1192
- * Excludes the root application alias.
1193
- *
1194
- * @param cli - The mounted command instance.
1195
- */
1196
- /**
1197
- * Flatten a plugin tree into a list of `{ plugin, path }` entries.
1198
- * Traverses the namespace chain in pre-order.
1199
- */
1200
- function flattenPluginTreeByPath(plugins, prefix) {
1201
- const out = [];
1202
- for (const p of plugins) {
1203
- const here = prefix && prefix.length > 0 ? `${prefix}/${p.ns}` : p.ns;
1204
- out.push({ plugin: p, path: here });
1205
- if (Array.isArray(p.children) && p.children.length > 0) {
1206
- out.push(...flattenPluginTreeByPath(p.children.map((c) => c.plugin), here));
1207
- }
1208
- }
1209
- return out;
1210
- }
1211
-
1212
- /**
1213
- * Instance-bound plugin config store.
1214
- * Host stores the validated/interpolated slice per plugin instance.
1215
- * The store is intentionally private to this module; definePlugin()
1216
- * provides a typed accessor that reads from this store for the calling
1217
- * plugin instance.
1218
- */
1219
- const PLUGIN_CONFIG_STORE = new WeakMap();
1220
- /**
1221
- * Store a validated, interpolated config slice for a specific plugin instance.
1222
- * Generic on both the host options type and the plugin config type to avoid
1223
- * defaulting to GetDotenvOptions under exactOptionalPropertyTypes.
1224
- */
1225
- const setPluginConfig = (plugin, cfg) => {
1226
- PLUGIN_CONFIG_STORE.set(plugin, cfg);
1227
- };
1228
- /**
1229
- * Retrieve the validated/interpolated config slice for a plugin instance.
1230
- */
1231
- const getPluginConfig = (plugin) => {
1232
- return PLUGIN_CONFIG_STORE.get(plugin);
1233
- };
1234
- /**
1235
- * Compute the dotenv context for the host (uses the config loader/overlay path).
1236
- * - Resolves and validates options strictly (host-only).
1237
- * - Applies file cascade, overlays, dynamics, and optional effects.
1238
- * - Merges and validates per-plugin config slices (when provided), keyed by
1239
- * realized mount path (ns chain).
1240
- *
1241
- * @param customOptions - Partial options from the current invocation.
1242
- * @param plugins - Installed plugins (for config validation).
1243
- * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery).
1244
- */
1245
- const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1246
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1247
- // Zod boundary: parse returns the schema-derived shape; we adopt our public
1248
- // GetDotenvOptions overlay (logger/dynamic typing) for internal processing.
1249
- const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1250
- // Build a pure base without side effects or logging (no dynamics, no programmatic vars).
1251
- const cleanedValidated = omitUndefined(validated);
1252
- const base = await getDotenv({
1253
- ...cleanedValidated,
1254
- excludeDynamic: true,
1255
- vars: {},
1256
- log: false,
1257
- loadProcess: false,
1258
- });
1259
- // Discover config sources and overlay with progressive expansion per slice.
1260
- const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1261
- const dotenvOverlaid = overlayEnv({
1262
- base,
1263
- env: validated.env ?? validated.defaultEnv,
1264
- configs: sources,
1265
- ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1266
- });
1267
- const dotenv = { ...dotenvOverlaid };
1268
- // Programmatic dynamic variables (when provided)
1269
- applyDynamicMap(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1270
- // Packaged/project dynamics
1271
- const packagedDyn = (sources.packaged?.dynamic ?? undefined);
1272
- const publicDyn = (sources.project?.public?.dynamic ?? undefined);
1273
- const localDyn = (sources.project?.local?.dynamic ?? undefined);
1274
- applyDynamicMap(dotenv, packagedDyn, validated.env ?? validated.defaultEnv);
1275
- applyDynamicMap(dotenv, publicDyn, validated.env ?? validated.defaultEnv);
1276
- applyDynamicMap(dotenv, localDyn, validated.env ?? validated.defaultEnv);
1277
- // file dynamicPath (lowest)
1278
- if (validated.dynamicPath) {
1279
- const absDynamicPath = path.resolve(validated.dynamicPath);
1280
- await loadAndApplyDynamic(dotenv, absDynamicPath, validated.env ?? validated.defaultEnv, 'getdotenv-dynamic-host');
1281
- }
1282
- // Effects:
1283
- if (validated.outputPath) {
1284
- await writeDotenvFile(validated.outputPath, dotenv);
1285
- }
1286
- const logger = validated.logger;
1287
- if (validated.log)
1288
- logger.log(dotenv);
1289
- if (validated.loadProcess)
1290
- Object.assign(process.env, dotenv);
1291
- // Merge and validate per-plugin config keyed by realized path (ns chain).
1292
- const packagedPlugins = (sources.packaged &&
1293
- sources.packaged.plugins) ??
1294
- {};
1295
- const publicPlugins = (sources.project?.public &&
1296
- sources.project.public.plugins) ??
1297
- {};
1298
- const localPlugins = (sources.project?.local &&
1299
- sources.project.local.plugins) ??
1300
- {};
1301
- const entries = flattenPluginTreeByPath(plugins);
1302
- const mergedPluginConfigsByPath = {};
1303
- const envRef = {
1304
- ...dotenv,
1305
- ...process.env,
1306
- };
1307
- for (const e of entries) {
1308
- const pathKey = e.path;
1309
- const mergedRaw = defaultsDeep({}, packagedPlugins[pathKey] ?? {}, publicPlugins[pathKey] ?? {}, localPlugins[pathKey] ?? {});
1310
- const interpolated = mergedRaw && typeof mergedRaw === 'object'
1311
- ? interpolateDeep(mergedRaw, envRef)
1312
- : {};
1313
- const schema = e.plugin.configSchema;
1314
- if (schema) {
1315
- const parsed = schema.safeParse(interpolated);
1316
- if (!parsed.success) {
1317
- const err = parsed.error;
1318
- const msgs = err.issues
1319
- .map((i) => {
1320
- const pth = Array.isArray(i.path) ? i.path.join('.') : '';
1321
- const msg = typeof i.message === 'string' ? i.message : 'Invalid value';
1322
- return pth ? `${pth}: ${msg}` : msg;
1323
- })
1324
- .join('\n');
1325
- throw new Error(`Invalid config for plugin at '${pathKey}':\n${msgs}`);
1326
- }
1327
- const frozen = Object.freeze(parsed.data);
1328
- setPluginConfig(e.plugin, frozen);
1329
- mergedPluginConfigsByPath[pathKey] = frozen;
1330
- }
1331
- else {
1332
- const frozen = Object.freeze(interpolated);
1333
- setPluginConfig(e.plugin, frozen);
1334
- mergedPluginConfigsByPath[pathKey] = frozen;
1335
- }
1336
- }
1337
- return {
1338
- optionsResolved: validated,
1339
- dotenv,
1340
- plugins: {},
1341
- pluginConfigs: mergedPluginConfigsByPath,
1342
- };
1343
- };
1344
-
1345
- // Implementation
1346
- function definePlugin(spec) {
1347
- const { ...rest } = spec;
1348
- const effectiveSchema = spec.configSchema ?? z.object({}).strict();
1349
- const base = {
1350
- ...rest,
1351
- configSchema: effectiveSchema,
1352
- children: [],
1353
- use(child, override) {
1354
- // Enforce sibling uniqueness at composition time.
1355
- const desired = (override && typeof override.ns === 'string' && override.ns.length > 0
1356
- ? override.ns
1357
- : child.ns).trim();
1358
- const collision = this.children.some((c) => {
1359
- const ns = (c.override &&
1360
- typeof c.override.ns === 'string' &&
1361
- c.override.ns.length > 0
1362
- ? c.override.ns
1363
- : c.plugin.ns).trim();
1364
- return ns === desired;
1365
- });
1366
- if (collision) {
1367
- const under = this.ns && this.ns.length > 0 ? this.ns : 'root';
1368
- throw new Error(`Duplicate namespace '${desired}' under '${under}'. ` +
1369
- `Override via .use(plugin, { ns: '...' }).`);
1370
- }
1371
- this.children.push({ plugin: child, override });
1372
- return this;
1373
- },
1374
- };
1375
- const extended = base;
1376
- extended.readConfig = function (_cli) {
1377
- const value = getPluginConfig(extended);
1378
- if (value === undefined) {
1379
- throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
1380
- }
1381
- return value;
1382
- };
1383
- extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
1384
- // Derive realized path strictly from the provided mount (leaf-up).
1385
- const realizedPath = (() => {
1386
- const parts = [];
1387
- let node = cli;
1388
- while (node.parent) {
1389
- parts.push(node.name());
1390
- node = node.parent;
1391
- }
1392
- return parts.reverse().join('/');
1393
- })();
1394
- return cli.createDynamicOption(flags, (c) => {
1395
- const fromStore = getPluginConfig(extended);
1396
- let cfgVal = fromStore ?? {};
1397
- // Strict fallback only by realized path for help-time synthetic usage.
1398
- if (!fromStore && realizedPath.length > 0) {
1399
- const bag = c.plugins;
1400
- const maybe = bag[realizedPath];
1401
- if (maybe && typeof maybe === 'object') {
1402
- cfgVal = maybe;
1403
- }
1404
- }
1405
- // c is strictly typed as ResolvedHelpConfig from cli.createDynamicOption
1406
- return desc(c, cfgVal);
1407
- }, parser, defaultValue);
1408
- };
1409
- return extended;
1410
- }
1411
-
1412
- const dbg = (...args) => {
1413
- if (process.env.GETDOTENV_DEBUG) {
1414
- // Use stderr to avoid interfering with stdout assertions
1415
- console.error('[getdotenv:run]', ...args);
1416
- }
1417
- };
1418
- /**
1419
- * Helper to decide whether to capture child stdio.
1420
- * Checks GETDOTENV_STDIO env var or the provided bag capture flag.
1421
- */
1422
- const shouldCapture = (bagCapture) => process.env.GETDOTENV_STDIO === 'pipe' || Boolean(bagCapture);
1423
- // Strip repeated symmetric outer quotes (single or double) until stable.
1424
- // This is safe for argv arrays passed to execa (no quoting needed) and avoids
1425
- // passing quote characters through to Node (e.g., for `node -e "<code>"`).
1426
- // Handles stacked quotes from shells like PowerShell: """code""" -> code.
1427
- const stripOuterQuotes = (s) => {
1428
- let out = s;
1429
- // Repeatedly trim only when the entire string is wrapped in matching quotes.
1430
- // Stop as soon as the ends are asymmetric or no quotes remain.
1431
- while (out.length >= 2) {
1432
- const a = out.charAt(0);
1433
- const b = out.charAt(out.length - 1);
1434
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
1435
- if (!symmetric)
1436
- break;
1437
- out = out.slice(1, -1);
1438
- }
1439
- return out;
1440
- };
1441
- // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
1442
- const pickResult = (r) => {
1443
- const exit = r.exitCode;
1444
- const stdoutVal = r.stdout;
1445
- const stderrVal = r.stderr;
1446
- return {
1447
- exitCode: typeof exit === 'number' ? exit : Number.NaN,
1448
- stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
1449
- stderr: typeof stderrVal === 'string' ? stderrVal : '',
1450
- };
1451
- };
1452
- // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
1453
- // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
1454
- const sanitizeEnv = (env) => {
1455
- if (!env)
1456
- return undefined;
1457
- const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
1458
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
1459
- };
1460
- /**
1461
- * Core executor that normalizes shell/plain forms and capture/inherit modes.
1462
- * Returns captured buffers; callers may stream stdout when desired.
1463
- */
1464
- async function _execNormalized(command, shell, opts = {}) {
1465
- const envSan = sanitizeEnv(opts.env);
1466
- const timeoutBits = typeof opts.timeoutMs === 'number'
1467
- ? { timeout: opts.timeoutMs, killSignal: 'SIGKILL' }
1468
- : {};
1469
- const stdio = opts.stdio ?? 'pipe';
1470
- if (shell === false) {
1471
- let file;
1472
- let args = [];
1473
- if (typeof command === 'string') {
1474
- const tokens = tokenize(command);
1475
- file = tokens[0];
1476
- args = tokens.slice(1);
1477
- }
1478
- else {
1479
- file = command[0];
1480
- args = command.slice(1).map(stripOuterQuotes);
1481
- }
1482
- if (!file)
1483
- return { exitCode: 0, stdout: '', stderr: '' };
1484
- dbg('exec (plain)', { file, args, stdio });
1485
- try {
1486
- const ok = pickResult((await execa(file, args, {
1487
- ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
1488
- ...(envSan !== undefined ? { env: envSan } : {}),
1489
- stdio,
1490
- ...timeoutBits,
1491
- })));
1492
- dbg('exit (plain)', { exitCode: ok.exitCode });
1493
- return ok;
1494
- }
1495
- catch (e) {
1496
- const out = pickResult(e);
1497
- dbg('exit:error (plain)', { exitCode: out.exitCode });
1498
- return out;
1499
- }
1500
- }
1501
- // Shell path (string|true|URL): execaCommand handles shell resolution.
1502
- const commandStr = typeof command === 'string' ? command : command.join(' ');
1503
- dbg('exec (shell)', {
1504
- command: commandStr,
1505
- shell: typeof shell === 'string' ? shell : 'custom',
1506
- stdio,
1507
- });
1508
- try {
1509
- const ok = pickResult((await execaCommand(commandStr, {
1510
- shell,
1511
- ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
1512
- ...(envSan !== undefined ? { env: envSan } : {}),
1513
- stdio,
1514
- ...timeoutBits,
1515
- })));
1516
- dbg('exit (shell)', { exitCode: ok.exitCode });
1517
- return ok;
1518
- }
1519
- catch (e) {
1520
- const out = pickResult(e);
1521
- dbg('exit:error (shell)', { exitCode: out.exitCode });
1522
- return out;
1523
- }
1524
- }
1525
- /**
1526
- * Execute a command and capture stdout/stderr (buffered).
1527
- *
1528
- * @param command - Command string (shell) or argv array (shell-off supported).
1529
- * @param shell - Shell setting (false for plain execution).
1530
- * @param opts - Execution options (cwd/env/timeout).
1531
- * @returns A promise resolving to the captured result.
1532
- */
1533
- async function runCommandResult(command, shell, opts = {}) {
1534
- // Build opts without injecting undefined (exactOptionalPropertyTypes-safe)
1535
- const coreOpts = { stdio: 'pipe' };
1536
- if (opts.cwd !== undefined) {
1537
- coreOpts.cwd = opts.cwd;
1538
- }
1539
- if (opts.env !== undefined) {
1540
- coreOpts.env = opts.env;
1541
- }
1542
- if (opts.timeoutMs !== undefined) {
1543
- coreOpts.timeoutMs = opts.timeoutMs;
1544
- }
1545
- return _execNormalized(command, shell, coreOpts);
1546
- }
1547
- /**
1548
- * Execute a command and return its exit code.
1549
- *
1550
- * @param command - Command string (shell) or argv array (shell-off supported).
1551
- * @param shell - Shell setting (false for plain execution).
1552
- * @param opts - Execution options (cwd/env/stdio).
1553
- * @returns A promise resolving to the process exit code.
1554
- */
1555
- async function runCommand(command, shell, opts) {
1556
- // Build opts without injecting undefined (exactOptionalPropertyTypes-safe)
1557
- const callOpts = {};
1558
- if (opts.cwd !== undefined) {
1559
- callOpts.cwd = opts.cwd;
1560
- }
1561
- if (opts.env !== undefined) {
1562
- callOpts.env = opts.env;
1563
- }
1564
- if (opts.stdio !== undefined)
1565
- callOpts.stdio = opts.stdio;
1566
- const ok = await _execNormalized(command, shell, callOpts);
1567
- if (opts.stdio === 'pipe' && ok.stdout) {
1568
- process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
1569
- }
1570
- return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
1571
- }
1572
-
1573
- /**
1574
- * Attach root flags to a {@link GetDotenvCli} instance.
1575
- *
1576
- * Program is typed as {@link GetDotenvCli} and supports {@link GetDotenvCli.createDynamicOption | createDynamicOption}.
1577
- */
1578
- const attachRootOptions = (program, defaults) => {
1579
- const GROUP = 'base';
1580
- const { defaultEnv, dotenvToken, dynamicPath, env, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1581
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1582
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1583
- // Helper: append (default) tags for ON/OFF toggles
1584
- const onOff = (on, isDefault) => on
1585
- ? `ON${isDefault ? ' (default)' : ''}`
1586
- : `OFF${isDefault ? ' (default)' : ''}`;
1587
- program.enablePositionalOptions().passThroughOptions();
1588
- // -e, --env <string>
1589
- {
1590
- const opt = new Option('-e, --env <string>', 'target environment (dotenv-expanded)');
1591
- opt.argParser(dotenvExpandFromProcessEnv);
1592
- if (env !== undefined)
1593
- opt.default(env);
1594
- program.addOption(opt);
1595
- program.setOptionGroup(opt, GROUP);
1596
- }
1597
- // -v, --vars <string>
1598
- {
1599
- const examples = [
1600
- ['KEY1', 'VAL1'],
1601
- ['KEY2', 'VAL2'],
1602
- ]
1603
- .map((v) => v.join(va))
1604
- .join(vd);
1605
- const opt = new Option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${examples}`);
1606
- opt.argParser(dotenvExpandFromProcessEnv);
1607
- program.addOption(opt);
1608
- program.setOptionGroup(opt, GROUP);
1609
- }
1610
- // Output path (interpolated later; help can remain static)
1611
- {
1612
- const opt = new Option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)');
1613
- opt.argParser(dotenvExpandFromProcessEnv);
1614
- if (outputPath !== undefined)
1615
- opt.default(outputPath);
1616
- program.addOption(opt);
1617
- program.setOptionGroup(opt, GROUP);
1618
- }
1619
- // Shell ON (string or boolean true => default shell)
1620
- {
1621
- const opt = program
1622
- .createDynamicOption('-s, --shell [string]', (cfg) => {
1623
- const s = cfg.shell;
1624
- let tag = '';
1625
- if (typeof s === 'boolean' && s)
1626
- tag = ' (default OS shell)';
1627
- else if (typeof s === 'string' && s.length > 0)
1628
- tag = ` (default ${s})`;
1629
- return `command execution shell, no argument for default OS shell or provide shell string${tag}`;
1630
- })
1631
- .conflicts('shellOff');
1632
- program.addOption(opt);
1633
- program.setOptionGroup(opt, GROUP);
1634
- }
1635
- // Shell OFF
1636
- {
1637
- const opt = program
1638
- .createDynamicOption('-S, --shell-off', (cfg) => {
1639
- const s = cfg.shell;
1640
- return `command execution shell OFF${s === false ? ' (default)' : ''}`;
1641
- })
1642
- .conflicts('shell');
1643
- program.addOption(opt);
1644
- program.setOptionGroup(opt, GROUP);
1645
- }
1646
- // Load process ON/OFF (dynamic defaults)
1647
- {
1648
- const optOn = program
1649
- .createDynamicOption('-p, --load-process', (cfg) => `load variables to process.env ${onOff(true, Boolean(cfg.loadProcess))}`)
1650
- .conflicts('loadProcessOff');
1651
- program.addOption(optOn);
1652
- program.setOptionGroup(optOn, GROUP);
1653
- const optOff = program
1654
- .createDynamicOption('-P, --load-process-off', (cfg) => `load variables to process.env ${onOff(false, !cfg.loadProcess)}`)
1655
- .conflicts('loadProcess');
1656
- program.addOption(optOff);
1657
- program.setOptionGroup(optOff, GROUP);
1658
- }
1659
- // Exclusion master toggle (dynamic)
1660
- {
1661
- const optAll = program
1662
- .createDynamicOption('-a, --exclude-all', (cfg) => {
1663
- const allOn = !!cfg.excludeDynamic &&
1664
- ((!!cfg.excludeEnv && !!cfg.excludeGlobal) ||
1665
- (!!cfg.excludePrivate && !!cfg.excludePublic));
1666
- const suffix = allOn ? ' (default)' : '';
1667
- return `exclude all dotenv variables from loading ON${suffix}`;
1668
- })
1669
- .conflicts('excludeAllOff');
1670
- program.addOption(optAll);
1671
- program.setOptionGroup(optAll, GROUP);
1672
- const optAllOff = new Option('-A, --exclude-all-off', 'exclude all dotenv variables from loading OFF (default)').conflicts('excludeAll');
1673
- program.addOption(optAllOff);
1674
- program.setOptionGroup(optAllOff, GROUP);
1675
- }
1676
- // Per-family exclusions (dynamic defaults)
1677
- {
1678
- const o1 = program
1679
- .createDynamicOption('-z, --exclude-dynamic', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(true, Boolean(cfg.excludeDynamic))}`)
1680
- .conflicts('excludeDynamicOff');
1681
- program.addOption(o1);
1682
- program.setOptionGroup(o1, GROUP);
1683
- const o2 = program
1684
- .createDynamicOption('-Z, --exclude-dynamic-off', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(false, !cfg.excludeDynamic)}`)
1685
- .conflicts('excludeDynamic');
1686
- program.addOption(o2);
1687
- program.setOptionGroup(o2, GROUP);
1688
- }
1689
- {
1690
- const o1 = program
1691
- .createDynamicOption('-n, --exclude-env', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(true, Boolean(cfg.excludeEnv))}`)
1692
- .conflicts('excludeEnvOff');
1693
- program.addOption(o1);
1694
- program.setOptionGroup(o1, GROUP);
1695
- const o2 = program
1696
- .createDynamicOption('-N, --exclude-env-off', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(false, !cfg.excludeEnv)}`)
1697
- .conflicts('excludeEnv');
1698
- program.addOption(o2);
1699
- program.setOptionGroup(o2, GROUP);
1700
- }
1701
- {
1702
- const o1 = program
1703
- .createDynamicOption('-g, --exclude-global', (cfg) => `exclude global dotenv variables from loading ${onOff(true, Boolean(cfg.excludeGlobal))}`)
1704
- .conflicts('excludeGlobalOff');
1705
- program.addOption(o1);
1706
- program.setOptionGroup(o1, GROUP);
1707
- const o2 = program
1708
- .createDynamicOption('-G, --exclude-global-off', (cfg) => `exclude global dotenv variables from loading ${onOff(false, !cfg.excludeGlobal)}`)
1709
- .conflicts('excludeGlobal');
1710
- program.addOption(o2);
1711
- program.setOptionGroup(o2, GROUP);
1712
- }
1713
- {
1714
- const p1 = program
1715
- .createDynamicOption('-r, --exclude-private', (cfg) => `exclude private dotenv variables from loading ${onOff(true, Boolean(cfg.excludePrivate))}`)
1716
- .conflicts('excludePrivateOff');
1717
- program.addOption(p1);
1718
- program.setOptionGroup(p1, GROUP);
1719
- const p2 = program
1720
- .createDynamicOption('-R, --exclude-private-off', (cfg) => `exclude private dotenv variables from loading ${onOff(false, !cfg.excludePrivate)}`)
1721
- .conflicts('excludePrivate');
1722
- program.addOption(p2);
1723
- program.setOptionGroup(p2, GROUP);
1724
- const pu1 = program
1725
- .createDynamicOption('-u, --exclude-public', (cfg) => `exclude public dotenv variables from loading ${onOff(true, Boolean(cfg.excludePublic))}`)
1726
- .conflicts('excludePublicOff');
1727
- program.addOption(pu1);
1728
- program.setOptionGroup(pu1, GROUP);
1729
- const pu2 = program
1730
- .createDynamicOption('-U, --exclude-public-off', (cfg) => `exclude public dotenv variables from loading ${onOff(false, !cfg.excludePublic)}`)
1731
- .conflicts('excludePublic');
1732
- program.addOption(pu2);
1733
- program.setOptionGroup(pu2, GROUP);
1734
- }
1735
- // Log ON/OFF (dynamic)
1736
- {
1737
- const lo = program
1738
- .createDynamicOption('-l, --log', (cfg) => `console log loaded variables ${onOff(true, Boolean(cfg.log))}`)
1739
- .conflicts('logOff');
1740
- program.addOption(lo);
1741
- program.setOptionGroup(lo, GROUP);
1742
- const lf = program
1743
- .createDynamicOption('-L, --log-off', (cfg) => `console log loaded variables ${onOff(false, !cfg.log)}`)
1744
- .conflicts('log');
1745
- program.addOption(lf);
1746
- program.setOptionGroup(lf, GROUP);
1747
- }
1748
- // Capture flag (no default display; static)
1749
- {
1750
- const opt = new Option('--capture', 'capture child process stdio for commands (tests/CI)');
1751
- program.addOption(opt);
1752
- program.setOptionGroup(opt, GROUP);
1753
- }
1754
- // Core bootstrap/static flags (kept static in help)
1755
- {
1756
- const o1 = new Option('--default-env <string>', 'default target environment');
1757
- o1.argParser(dotenvExpandFromProcessEnv);
1758
- if (defaultEnv !== undefined)
1759
- o1.default(defaultEnv);
1760
- program.addOption(o1);
1761
- program.setOptionGroup(o1, GROUP);
1762
- const o2 = new Option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file');
1763
- o2.argParser(dotenvExpandFromProcessEnv);
1764
- if (dotenvToken !== undefined)
1765
- o2.default(dotenvToken);
1766
- program.addOption(o2);
1767
- program.setOptionGroup(o2, GROUP);
1768
- const o3 = new Option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)');
1769
- o3.argParser(dotenvExpandFromProcessEnv);
1770
- if (dynamicPath !== undefined)
1771
- o3.default(dynamicPath);
1772
- program.addOption(o3);
1773
- program.setOptionGroup(o3, GROUP);
1774
- const o4 = new Option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory');
1775
- o4.argParser(dotenvExpandFromProcessEnv);
1776
- if (paths !== undefined)
1777
- o4.default(paths);
1778
- program.addOption(o4);
1779
- program.setOptionGroup(o4, GROUP);
1780
- const o5 = new Option('--paths-delimiter <string>', 'paths delimiter string');
1781
- if (pathsDelimiter !== undefined)
1782
- o5.default(pathsDelimiter);
1783
- program.addOption(o5);
1784
- program.setOptionGroup(o5, GROUP);
1785
- const o6 = new Option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern');
1786
- if (pathsDelimiterPattern !== undefined)
1787
- o6.default(pathsDelimiterPattern);
1788
- program.addOption(o6);
1789
- program.setOptionGroup(o6, GROUP);
1790
- const o7 = new Option('--private-token <string>', 'dotenv-expanded token indicating private variables');
1791
- o7.argParser(dotenvExpandFromProcessEnv);
1792
- if (privateToken !== undefined)
1793
- o7.default(privateToken);
1794
- program.addOption(o7);
1795
- program.setOptionGroup(o7, GROUP);
1796
- const o8 = new Option('--vars-delimiter <string>', 'vars delimiter string');
1797
- if (varsDelimiter !== undefined)
1798
- o8.default(varsDelimiter);
1799
- program.addOption(o8);
1800
- program.setOptionGroup(o8, GROUP);
1801
- const o9 = new Option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern');
1802
- if (varsDelimiterPattern !== undefined)
1803
- o9.default(varsDelimiterPattern);
1804
- program.addOption(o9);
1805
- program.setOptionGroup(o9, GROUP);
1806
- const o10 = new Option('--vars-assignor <string>', 'vars assignment operator string');
1807
- if (varsAssignor !== undefined)
1808
- o10.default(varsAssignor);
1809
- program.addOption(o10);
1810
- program.setOptionGroup(o10, GROUP);
1811
- const o11 = new Option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern');
1812
- if (varsAssignorPattern !== undefined)
1813
- o11.default(varsAssignorPattern);
1814
- program.addOption(o11);
1815
- program.setOptionGroup(o11, GROUP);
1816
- }
1817
- // Diagnostics / validation / entropy
1818
- {
1819
- const tr = new Option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1820
- program.addOption(tr);
1821
- program.setOptionGroup(tr, GROUP);
1822
- const st = new Option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1823
- program.addOption(st);
1824
- program.setOptionGroup(st, GROUP);
1825
- }
1826
- {
1827
- const w = program
1828
- .createDynamicOption('--entropy-warn', (cfg) => {
1829
- const warn = cfg.warnEntropy;
1830
- // Default is effectively ON when warnEntropy is true or undefined.
1831
- return `enable entropy warnings${warn === false ? '' : ' (default on)'}`;
1832
- })
1833
- .conflicts('entropyWarnOff');
1834
- program.addOption(w);
1835
- program.setOptionGroup(w, GROUP);
1836
- const woff = program
1837
- .createDynamicOption('--entropy-warn-off', (cfg) => `disable entropy warnings${cfg.warnEntropy === false ? ' (default)' : ''}`)
1838
- .conflicts('entropyWarn');
1839
- program.addOption(woff);
1840
- program.setOptionGroup(woff, GROUP);
1841
- const th = new Option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)');
1842
- program.addOption(th);
1843
- program.setOptionGroup(th, GROUP);
1844
- const ml = new Option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)');
1845
- program.addOption(ml);
1846
- program.setOptionGroup(ml, GROUP);
1847
- const wl = new Option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern');
1848
- program.addOption(wl);
1849
- program.setOptionGroup(wl, GROUP);
1850
- const rp = new Option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1851
- program.addOption(rp);
1852
- program.setOptionGroup(rp, GROUP);
1853
- // Redact ON/OFF (dynamic)
1854
- {
1855
- const rOn = program
1856
- .createDynamicOption('--redact', (cfg) => `presentation-time redaction for secret-like keys ON${cfg.redact ? ' (default)' : ''}`)
1857
- .conflicts('redactOff');
1858
- program.addOption(rOn);
1859
- program.setOptionGroup(rOn, GROUP);
1860
- const rOff = program
1861
- .createDynamicOption('--redact-off', (cfg) => `presentation-time redaction for secret-like keys OFF${cfg.redact === false ? ' (default)' : ''}`)
1862
- .conflicts('redact');
1863
- program.addOption(rOff);
1864
- program.setOptionGroup(rOff, GROUP);
1865
- }
1866
- }
1867
- return program;
1868
- };
1869
-
1870
- /**
1871
- * Registry for option grouping.
1872
- * Root help renders these groups between "Options" and "Commands".
1873
- */
1874
- const GROUP_TAG = new WeakMap();
1875
- /**
1876
- * Render help option groups (App/Plugins) for a given command.
1877
- * Groups are injected between Options and Commands in the help output.
1878
- */
1879
- function renderOptionGroups(cmd) {
1880
- const all = cmd.options;
1881
- const byGroup = new Map();
1882
- for (const o of all) {
1883
- const opt = o;
1884
- const g = GROUP_TAG.get(opt);
1885
- if (!g || g === 'base')
1886
- continue; // base handled by default help
1887
- const rows = byGroup.get(g) ?? [];
1888
- rows.push({
1889
- flags: opt.flags,
1890
- description: opt.description ?? '',
1891
- });
1892
- byGroup.set(g, rows);
1893
- }
1894
- if (byGroup.size === 0)
1895
- return '';
1896
- const renderRows = (title, rows) => {
1897
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1898
- // Sort within group: short-aliased flags first
1899
- rows.sort((a, b) => {
1900
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1901
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1902
- return bS - aS || a.flags.localeCompare(b.flags);
1903
- });
1904
- const lines = rows
1905
- .map((r) => {
1906
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1907
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1908
- })
1909
- .join('\n');
1910
- return `\n${title}:\n${lines}\n`;
1911
- };
1912
- let out = '';
1913
- // App options (if any)
1914
- const app = byGroup.get('app');
1915
- if (app && app.length > 0) {
1916
- out += renderRows('App options', app);
1917
- }
1918
- // Plugin groups sorted by id; suppress self group on the owning command name.
1919
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1920
- const currentName = cmd.name();
1921
- pluginKeys.sort((a, b) => a.localeCompare(b));
1922
- for (const k of pluginKeys) {
1923
- const id = k.slice('plugin:'.length) || '(unknown)';
1924
- const rows = byGroup.get(k) ?? [];
1925
- if (rows.length > 0 && id !== currentName) {
1926
- out += renderRows(`Plugin options — ${id}`, rows);
1927
- }
1928
- }
1929
- return out;
1930
- }
1931
-
1932
- /**
1933
- * Compose root/parent help output by inserting grouped sections between
1934
- * Options and Commands, ensuring a trailing blank line.
1935
- *
1936
- * @param base - Base help text produced by Commander.
1937
- * @param cmd - Command instance whose grouped options should be rendered.
1938
- * @returns The modified help text with grouped blocks inserted.
1939
- */
1940
- function buildHelpInformation(base, cmd) {
1941
- const groups = renderOptionGroups(cmd);
1942
- const block = typeof groups === 'string' ? groups.trim() : '';
1943
- if (!block) {
1944
- return base.endsWith('\n\n')
1945
- ? base
1946
- : base.endsWith('\n')
1947
- ? `${base}\n`
1948
- : `${base}\n\n`;
1949
- }
1950
- const marker = '\nCommands:';
1951
- const idx = base.indexOf(marker);
1952
- let out = base;
1953
- if (idx >= 0) {
1954
- const toInsert = groups.startsWith('\n') ? groups : `\n${groups}`;
1955
- out = `${base.slice(0, idx)}${toInsert}${base.slice(idx)}`;
1956
- }
1957
- else {
1958
- const sep = base.endsWith('\n') || groups.startsWith('\n') ? '' : '\n';
1959
- out = `${base}${sep}${groups}`;
1960
- }
1961
- return out.endsWith('\n\n')
1962
- ? out
1963
- : out.endsWith('\n')
1964
- ? `${out}\n`
1965
- : `${out}\n\n`;
1966
- }
1967
-
1968
- /** src/cliHost/GetDotenvCli/dynamicOptions.ts
1969
- * Helpers for dynamic option descriptions and evaluation.
1970
- */
1971
- /**
1972
- * Registry for dynamic descriptions keyed by Option (WeakMap for GC safety).
1973
- */
1974
- const DYN_DESC = new WeakMap();
1975
- /**
1976
- * Create an Option with a dynamic description callback stored in DYN_DESC.
1977
- */
1978
- function makeDynamicOption(flags, desc, parser, defaultValue) {
1979
- const opt = new Option(flags, '');
1980
- DYN_DESC.set(opt, desc);
1981
- if (parser) {
1982
- opt.argParser((value, previous) => parser(value, previous));
1983
- }
1984
- if (defaultValue !== undefined)
1985
- opt.default(defaultValue);
1986
- // Commander.Option is structurally compatible; help-time wiring is stored in DYN_DESC.
1987
- return opt;
1988
- }
1989
- /**
1990
- * Evaluate dynamic descriptions across a command tree using the resolved config.
1991
- */
1992
- function evaluateDynamicOptions(root, resolved) {
1993
- const visit = (cmd) => {
1994
- const arr = cmd.options;
1995
- for (const o of arr) {
1996
- const dyn = DYN_DESC.get(o);
1997
- if (typeof dyn === 'function') {
1998
- try {
1999
- const txt = dyn(resolved);
2000
- // Commander uses Option.description during help rendering.
2001
- o.description = txt;
2002
- }
2003
- catch {
2004
- /* best-effort; leave as-is */
2005
- }
2006
- }
2007
- }
2008
- for (const c of cmd.commands)
2009
- visit(c);
2010
- };
2011
- visit(root);
2012
- }
2013
-
2014
- /**
2015
- * Initialize a {@link GetDotenvCli} instance with help configuration and safe defaults.
2016
- *
2017
- * @remarks
2018
- * This is a low-level initializer used by the host constructor to keep `GetDotenvCli.ts`
2019
- * small and to centralize help/output behavior.
2020
- *
2021
- * @param cli - The CLI instance to initialize.
2022
- * @param headerGetter - Callback returning an optional help header string.
2023
- */
2024
- function initializeInstance(cli, headerGetter) {
2025
- // Configure grouped help: show only base options in default "Options";
2026
- // subcommands show all of their own options.
2027
- cli.configureHelp({
2028
- visibleOptions: (cmd) => {
2029
- const all = cmd.options;
2030
- const isRoot = cmd.parent === null;
2031
- const list = isRoot
2032
- ? all.filter((opt) => {
2033
- const group = GROUP_TAG.get(opt);
2034
- return group === 'base';
2035
- })
2036
- : all.slice();
2037
- // Sort: short-aliased options first, then long-only; stable by flags.
2038
- const hasShort = (opt) => {
2039
- const flags = opt.flags;
2040
- return /(^|\s|,)-[A-Za-z]/.test(flags);
2041
- };
2042
- const byFlags = (opt) => opt.flags;
2043
- list.sort((a, b) => {
2044
- const aS = hasShort(a) ? 1 : 0;
2045
- const bS = hasShort(b) ? 1 : 0;
2046
- return bS - aS || byFlags(a).localeCompare(byFlags(b));
2047
- });
2048
- return list;
2049
- },
2050
- });
2051
- // Optional branded header before help text (kept minimal and deterministic).
2052
- cli.addHelpText('beforeAll', () => {
2053
- const header = headerGetter();
2054
- return header && header.length > 0 ? `${header}\n\n` : '';
2055
- });
2056
- // Tests-only: suppress process.exit during help/version flows under Vitest.
2057
- // Unit tests often construct GetDotenvCli directly (bypassing createCli),
2058
- // so install a local exitOverride when a test environment is detected.
2059
- const underTests = process.env.GETDOTENV_TEST === '1' ||
2060
- typeof process.env.VITEST_WORKER_ID === 'string';
2061
- if (underTests) {
2062
- cli.exitOverride((err) => {
2063
- const code = err?.code;
2064
- if (code === 'commander.helpDisplayed' ||
2065
- code === 'commander.version' ||
2066
- code === 'commander.help')
2067
- return;
2068
- throw err;
2069
- });
2070
- }
2071
- // Ensure the root has a no-op action so preAction hooks installed by
2072
- // passOptions() fire for root-only invocations (no subcommand).
2073
- // Subcommands still take precedence and will not hit this action.
2074
- // This keeps root-side effects (e.g., --log) working in direct hosts/tests.
2075
- cli.action(() => {
2076
- /* no-op */
2077
- });
2078
- // PreSubcommand hook: compute a context if absent, without mutating process.env.
2079
- // The passOptions() helper, when installed, resolves the final context.
2080
- cli.hook('preSubcommand', async () => {
2081
- if (cli.hasCtx())
2082
- return;
2083
- await cli.resolveAndLoad({ loadProcess: false });
2084
- });
2085
- }
2086
-
2087
- /**
2088
- * Determine the effective namespace for a child plugin (override \> default).
2089
- */
2090
- const effectiveNs = (child) => {
2091
- const o = child.override;
2092
- return (o && typeof o.ns === 'string' && o.ns.length > 0 ? o.ns : child.plugin.ns).trim();
2093
- };
2094
- const isPromise = (v) => !!v && typeof v.then === 'function';
2095
- function runInstall(parentCli, plugin) {
2096
- // Create mount and run setup
2097
- const mount = parentCli.ns(plugin.ns);
2098
- const setupRet = plugin.setup(mount);
2099
- const pending = [];
2100
- if (isPromise(setupRet))
2101
- pending.push(setupRet.then(() => undefined));
2102
- // Enforce sibling uniqueness before creating children
2103
- const names = new Set();
2104
- for (const entry of plugin.children) {
2105
- const ns = effectiveNs(entry);
2106
- if (names.has(ns)) {
2107
- const under = mount.name();
2108
- throw new Error(`Duplicate namespace '${ns}' under '${under || 'root'}'. Override via .use(plugin, { ns: '...' }).`);
2109
- }
2110
- names.add(ns);
2111
- }
2112
- // Install children (pre-order), synchronously when possible
2113
- for (const entry of plugin.children) {
2114
- const childRet = runInstall(mount, entry.plugin);
2115
- if (isPromise(childRet))
2116
- pending.push(childRet);
2117
- }
2118
- if (pending.length > 0)
2119
- return Promise.all(pending).then(() => undefined);
2120
- return;
2121
- }
2122
- /**
2123
- * Install a plugin and its children (pre-order setup phase).
2124
- * Enforces sibling namespace uniqueness.
2125
- */
2126
- function setupPluginTree(cli, plugin) {
2127
- const ret = runInstall(cli, plugin);
2128
- return isPromise(ret) ? ret : Promise.resolve();
2129
- }
2130
-
2131
- /**
2132
- * Resolve options strictly and compute the dotenv context via the loader/overlay path.
2133
- *
2134
- * @param customOptions - Partial options overlay.
2135
- * @param plugins - Plugins list for config validation.
2136
- * @param hostMetaUrl - Import URL for resolving the packaged root.
2137
- */
2138
- async function resolveAndComputeContext(customOptions, plugins, hostMetaUrl) {
2139
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
2140
- // Strict schema validation
2141
- getDotenvOptionsSchemaResolved.parse(optionsResolved);
2142
- const ctx = await computeContext(optionsResolved, plugins, hostMetaUrl);
2143
- return ctx;
2144
- }
2145
-
2146
- /**
2147
- * Run afterResolve hooks for a plugin tree (parent → children).
2148
- */
2149
- async function runAfterResolveTree(cli, plugins, ctx) {
2150
- const run = async (p) => {
2151
- if (p.afterResolve)
2152
- await p.afterResolve(cli, ctx);
2153
- for (const child of p.children)
2154
- await run(child.plugin);
2155
- };
2156
- for (const p of plugins)
2157
- await run(p);
2158
- }
2159
-
2160
- /**
2161
- * Temporarily tag options added during a callback as 'app' for grouped help.
2162
- * Wraps `addOption` on the command instance.
2163
- */
2164
- function tagAppOptionsAround(root, setOptionGroup, fn) {
2165
- const originalAddOption = root.addOption.bind(root);
2166
- root.addOption = ((opt) => {
2167
- setOptionGroup(opt, 'app');
2168
- return originalAddOption(opt);
2169
- });
2170
- try {
2171
- return fn(root);
2172
- }
2173
- finally {
2174
- root.addOption = originalAddOption;
2175
- }
2176
- }
2177
-
2178
- /**
2179
- * Read the version from the nearest `package.json` relative to the provided import URL.
2180
- *
2181
- * @param importMetaUrl - The `import.meta.url` of the calling module.
2182
- * @returns The version string or undefined if not found.
2183
- */
2184
- async function readPkgVersion(importMetaUrl) {
2185
- if (!importMetaUrl)
2186
- return undefined;
2187
- try {
2188
- const fromUrl = fileURLToPath(importMetaUrl);
2189
- const pkgDir = await packageDirectory({ cwd: fromUrl });
2190
- if (!pkgDir)
2191
- return undefined;
2192
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
2193
- const pkg = JSON.parse(txt);
2194
- return pkg.version ?? undefined;
2195
- }
2196
- catch {
2197
- // best-effort only
2198
- return undefined;
2199
- }
2200
- }
2201
-
2202
- /** src/cliHost/GetDotenvCli.ts
2203
- * Plugin-first CLI host for get-dotenv with Commander generics preserved.
2204
- * Public surface implements GetDotenvCliPublic and provides:
2205
- * - attachRootOptions (builder-only; no public override wiring)
2206
- * - resolveAndLoad (strict resolve + context compute)
2207
- * - getCtx/hasCtx accessors
2208
- * - ns() for typed subcommand creation with duplicate-name guard
2209
- * - grouped help rendering with dynamic option descriptions
2210
- */
2211
- const HOST_META_URL = import.meta.url;
2212
- const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
2213
- const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
2214
- const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
2215
- /**
2216
- * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
2217
- *
2218
- * Responsibilities:
2219
- * - Resolve options strictly and compute dotenv context (resolveAndLoad).
2220
- * - Expose a stable accessor for the current context (getCtx).
2221
- * - Provide a namespacing helper (ns).
2222
- * - Support composable plugins with parent → children install and afterResolve.
2223
- */
2224
- class GetDotenvCli extends Command {
2225
- /** Registered top-level plugins (composition happens via .use()) */
2226
- _plugins = [];
2227
- /** One-time installation guard */
2228
- _installed = false;
2229
- /** In-flight installation promise to guard against concurrent installs */
2230
- _installing;
2231
- /** Optional header line to prepend in help output */
2232
- [HELP_HEADER_SYMBOL];
2233
- /** Context/options stored under symbols (typed) */
2234
- [CTX_SYMBOL];
2235
- [OPTS_SYMBOL];
2236
- /**
2237
- * Create a subcommand using the same subclass, preserving helpers like
2238
- * dynamicOption on children.
2239
- */
2240
- createCommand(name) {
2241
- // Explicitly construct a GetDotenvCli for children to preserve helpers.
2242
- return new GetDotenvCli(name);
2243
- }
2244
- constructor(alias = 'getdotenv') {
2245
- super(alias);
2246
- this.enablePositionalOptions();
2247
- // Delegate the heavy setup to a helper to keep the constructor lean.
2248
- initializeInstance(this, () => this[HELP_HEADER_SYMBOL]);
2249
- }
2250
- /**
2251
- * Attach legacy/base root flags to this CLI instance.
2252
- * Delegates to the pure builder in attachRootOptions.ts.
2253
- */
2254
- attachRootOptions(defaults) {
2255
- const d = (defaults ?? baseRootOptionDefaults);
2256
- attachRootOptions(this, d);
2257
- return this;
2258
- }
2259
- /**
2260
- * Resolve options (strict) and compute dotenv context.
2261
- * Stores the context on the instance under a symbol.
2262
- *
2263
- * Options:
2264
- * - opts.runAfterResolve (default true): when false, skips running plugin
2265
- * afterResolve hooks. Useful for top-level help rendering to avoid
2266
- * long-running side-effects while still evaluating dynamic help text.
2267
- */
2268
- async resolveAndLoad(customOptions = {}, opts) {
2269
- const ctx = await resolveAndComputeContext(customOptions,
2270
- // Pass only plugin instances to the resolver (not entries with overrides)
2271
- this._plugins.map((e) => e.plugin), HOST_META_URL);
2272
- // Persist context on the instance for later access.
2273
- this[CTX_SYMBOL] = ctx;
2274
- // Ensure plugins are installed exactly once, then run afterResolve.
2275
- await this.install();
2276
- if (opts?.runAfterResolve ?? true) {
2277
- await this._runAfterResolve(ctx);
2278
- }
2279
- return ctx;
2280
- }
2281
- // Implementation
2282
- createDynamicOption(flags, desc, parser, defaultValue) {
2283
- return makeDynamicOption(flags, (c) => desc(c), parser, defaultValue);
2284
- }
2285
- /**
2286
- * Evaluate dynamic descriptions for this command and all descendants using
2287
- * the provided resolved configuration. Mutates the Option.description in
2288
- * place so Commander help renders updated text.
2289
- */
2290
- evaluateDynamicOptions(resolved) {
2291
- evaluateDynamicOptions(this, resolved);
2292
- }
2293
- /** Internal: climb to the true root (host) command. */
2294
- _root() {
2295
- let node = this;
2296
- while (node.parent) {
2297
- node = node.parent;
2298
- }
2299
- return node;
2300
- }
2301
- /**
2302
- * Retrieve the current invocation context (if any).
2303
- */
2304
- getCtx() {
2305
- let ctx = this[CTX_SYMBOL];
2306
- if (!ctx) {
2307
- const root = this._root();
2308
- ctx = root[CTX_SYMBOL];
2309
- }
2310
- if (!ctx) {
2311
- throw new Error('Dotenv context unavailable. Ensure resolveAndLoad() has been called or the host is wired with passOptions() before invoking commands.');
2312
- }
2313
- return ctx;
2314
- }
2315
- /**
2316
- * Check whether a context has been resolved (non-throwing guard).
2317
- */
2318
- hasCtx() {
2319
- if (this[CTX_SYMBOL] !== undefined)
2320
- return true;
2321
- const root = this._root();
2322
- return root[CTX_SYMBOL] !== undefined;
2323
- }
2324
- /**
2325
- * Retrieve the merged root CLI options bag (if set by passOptions()).
2326
- * Downstream-safe: no generics required.
2327
- */
2328
- getOptions() {
2329
- if (this[OPTS_SYMBOL])
2330
- return this[OPTS_SYMBOL];
2331
- const root = this._root();
2332
- const bag = root[OPTS_SYMBOL];
2333
- if (bag)
2334
- return bag;
2335
- return undefined;
2336
- }
2337
- /** Internal: set the merged root options bag for this run. */
2338
- _setOptionsBag(bag) {
2339
- this[OPTS_SYMBOL] = bag;
2340
- }
2341
- /**
2342
- * Convenience helper to create a namespaced subcommand with argument inference.
2343
- * This mirrors Commander generics so downstream chaining stays fully typed.
2344
- */
2345
- ns(name) {
2346
- // Guard against same-level duplicate command names for clearer diagnostics.
2347
- const exists = this.commands.some((c) => c.name() === name);
2348
- if (exists) {
2349
- throw new Error(`Duplicate command name: ${name}`);
2350
- }
2351
- return this.command(name);
2352
- }
2353
- /**
2354
- * Tag options added during the provided callback as 'app' for grouped help.
2355
- * Allows downstream apps to demarcate their root-level options.
2356
- */
2357
- tagAppOptions(fn) {
2358
- return tagAppOptionsAround(this, this.setOptionGroup.bind(this), fn);
2359
- }
2360
- /**
2361
- * Branding helper: set CLI name/description/version and optional help header.
2362
- * If version is omitted and importMetaUrl is provided, attempts to read the
2363
- * nearest package.json version (best-effort; non-fatal on failure).
2364
- */
2365
- async brand(args) {
2366
- const { name, description, version, importMetaUrl, helpHeader } = args;
2367
- if (typeof name === 'string' && name.length > 0)
2368
- this.name(name);
2369
- if (typeof description === 'string')
2370
- this.description(description);
2371
- const v = version ?? (await readPkgVersion(importMetaUrl));
2372
- if (v)
2373
- this.version(v);
2374
- // Help header:
2375
- // - If caller provides helpHeader, use it.
2376
- // - Otherwise, when a version is known, default to "<name> v<version>".
2377
- if (typeof helpHeader === 'string') {
2378
- this[HELP_HEADER_SYMBOL] = helpHeader;
2379
- }
2380
- else if (v) {
2381
- const header = `${this.name()} v${v}`;
2382
- this[HELP_HEADER_SYMBOL] = header;
2383
- }
2384
- return this;
2385
- }
2386
- /**
2387
- * Insert grouped plugin/app options between "Options" and "Commands" for
2388
- * hybrid ordering. Applies to root and any parent command.
2389
- */
2390
- helpInformation() {
2391
- return buildHelpInformation(super.helpInformation(), this);
2392
- }
2393
- /**
2394
- * Public: tag an Option with a display group for help (root/app/plugin:<id>).
2395
- */
2396
- setOptionGroup(opt, group) {
2397
- GROUP_TAG.set(opt, group);
2398
- }
2399
- /**
2400
- * Register a plugin for installation (parent level).
2401
- * Installation occurs on first resolveAndLoad() (or explicit install()).
2402
- */
2403
- use(plugin, override) {
2404
- this._plugins.push({ plugin, override });
2405
- return this;
2406
- }
2407
- /**
2408
- * Install all registered plugins in parent → children (pre-order).
2409
- * Runs only once per CLI instance.
2410
- */
2411
- async install() {
2412
- if (this._installed)
2413
- return;
2414
- if (this._installing) {
2415
- await this._installing;
2416
- return;
2417
- }
2418
- this._installing = (async () => {
2419
- // Install parent → children with host-created mounts (async-aware).
2420
- for (const entry of this._plugins) {
2421
- const p = entry.plugin;
2422
- await setupPluginTree(this, p);
2423
- }
2424
- this._installed = true;
2425
- })();
2426
- try {
2427
- await this._installing;
2428
- }
2429
- finally {
2430
- // leave _installing as resolved; subsequent calls return early via _installed
2431
- }
2432
- }
2433
- /**
2434
- * Run afterResolve hooks for all plugins (parent → children).
2435
- */
2436
- async _runAfterResolve(ctx) {
2437
- await runAfterResolveTree(this, this._plugins.map((e) => e.plugin), ctx);
2438
- }
2439
- }
2440
-
2441
- /**
2442
- * Retrieve the merged root options bag from the current command context.
2443
- * Climbs to the root `GetDotenvCli` instance to access the persisted options.
2444
- *
2445
- * @param cmd - The current command instance (thisCommand).
2446
- * @throws Error if the root is not a GetDotenvCli or options are missing.
2447
- */
2448
- const readMergedOptions = (cmd) => {
2449
- // Climb to the true root
2450
- let root = cmd;
2451
- while (root.parent)
2452
- root = root.parent;
2453
- // Assert we ended at our host
2454
- if (!(root instanceof GetDotenvCli)) {
2455
- throw new Error('readMergedOptions: root command is not a GetDotenvCli.' +
2456
- 'Ensure your CLI is constructed with GetDotenvCli.');
2457
- }
2458
- // Require passOptions() to have persisted the bag
2459
- const bag = root.getOptions();
2460
- if (!bag || typeof bag !== 'object') {
2461
- throw new Error('readMergedOptions: merged options are unavailable. ' +
2462
- 'Call .passOptions() on the host before parsing.');
2463
- }
2464
- return bag;
2465
- };
2466
-
2467
- /**
2468
- * Batch services (neutral): resolve command and shell settings.
2469
- * Shared by the generator path and the batch plugin to avoid circular deps.
2470
- */
2471
- /**
2472
- * Resolve a command string from the {@link ScriptsTable} table.
2473
- * A script may be expressed as a string or an object with a `cmd` property.
2474
- *
2475
- * @param scripts - Optional scripts table.
2476
- * @param command - User-provided command name or string.
2477
- * @returns Resolved command string (falls back to the provided command).
2478
- */
2479
- /**
2480
- * Resolve the shell setting for a given command:
2481
- * - If the script entry is an object, prefer its `shell` override.
2482
- * - Otherwise use the provided `shell` (string | boolean).
2483
- *
2484
- * @param scripts - Optional scripts table.
2485
- * @param command - User-provided command name or string.
2486
- * @param shell - Global shell preference (string | boolean).
2487
- */
2488
- const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
2489
- ? (scripts[command].shell ?? false)
2490
- : (shell ?? false);
2491
-
2492
- const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
2493
- /**
2494
- * Build a sanitized environment object for spawning child processes.
2495
- * Merges `base` and `overlay`, drops undefined values, and handles platform-specific
2496
- * normalization (e.g. case-insensitivity on Windows).
2497
- *
2498
- * @param base - Base environment (usually `process.env`).
2499
- * @param overlay - Environment variables to overlay.
2500
- */
2501
- const buildSpawnEnv = (base, overlay) => {
2502
- const raw = {
2503
- ...(base ?? {}),
2504
- ...(overlay ?? {}),
2505
- };
2506
- // Drop undefined first
2507
- const entries = Object.entries(dropUndefined(raw));
2508
- if (process.platform === 'win32') {
2509
- // Windows: keys are case-insensitive; collapse duplicates
2510
- const byLower = new Map();
2511
- for (const [k, v] of entries) {
2512
- byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
2513
- }
2514
- const out = {};
2515
- for (const [, [k, v]] of byLower)
2516
- out[k] = v;
2517
- // HOME fallback from USERPROFILE (common expectation)
2518
- if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
2519
- const up = out['USERPROFILE'];
2520
- if (typeof up === 'string' && up.length > 0)
2521
- out['HOME'] = up;
2522
- }
2523
- // Normalize TMP/TEMP coherence (pick any present; reflect to both)
2524
- const tmp = out['TMP'] ?? out['TEMP'];
2525
- if (typeof tmp === 'string' && tmp.length > 0) {
2526
- out['TMP'] = tmp;
2527
- out['TEMP'] = tmp;
2528
- }
2529
- return out;
2530
- }
2531
- // POSIX: keep keys as-is
2532
- const out = Object.fromEntries(entries);
2533
- // Ensure TMPDIR exists when any temp key is present (best-effort)
2534
- const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
2535
- if (typeof tmpdir === 'string' && tmpdir.length > 0) {
2536
- out['TMPDIR'] = tmpdir;
2537
- }
2538
- return out;
2539
- };
14
+ import { r as runCommand, a as runCommandResult, s as shouldCapture, d as resolveShell, b as buildSpawnEnv } from './chunks/spawnEnv-CN8a7cNR.mjs';
15
+ import './chunks/overlayEnv-Bs2kVayG.mjs';
16
+ import './chunks/loadModuleDefault-Dj8B3Stt.mjs';
2540
17
 
2541
18
  /**
2542
19
  * Apply resolved AWS context to `process.env` and `ctx.plugins`.
@@ -2603,7 +80,19 @@ function applyAwsContext(out, ctx, setProcessEnv = true) {
2603
80
  };
2604
81
  }
2605
82
 
2606
- const AWS_CLI_TIMEOUT_MS = 15_000;
83
+ // Keep AWS CLI probing bounded so the aws plugin does not stall unrelated commands.
84
+ // This is especially important when a profile is present but SSO refresh/export
85
+ // is slow or blocked (common on Windows).
86
+ const AWS_CLI_TIMEOUT_MS = 3_000;
87
+ const AWS_CLI_BUDGET_MS = 9_000;
88
+ const pickTimeoutMs = (deadlineMs) => {
89
+ if (typeof deadlineMs !== 'number')
90
+ return AWS_CLI_TIMEOUT_MS;
91
+ const remaining = deadlineMs - Date.now();
92
+ if (remaining <= 0)
93
+ return 0;
94
+ return Math.min(AWS_CLI_TIMEOUT_MS, remaining);
95
+ };
2607
96
  const trim = (s) => (typeof s === 'string' ? s.trim() : '');
2608
97
  const unquote = (s) => s.length >= 2 &&
2609
98
  ((s.startsWith('"') && s.endsWith('"')) ||
@@ -2687,7 +176,10 @@ const parseExportCredentialsEnv = (txt) => {
2687
176
  };
2688
177
  return undefined;
2689
178
  };
2690
- const getAwsConfigure = async (key, profile, timeoutMs = AWS_CLI_TIMEOUT_MS) => {
179
+ const getAwsConfigure = async (key, profile, deadlineMs) => {
180
+ const timeoutMs = pickTimeoutMs(deadlineMs);
181
+ if (timeoutMs <= 0)
182
+ return undefined;
2691
183
  const r = await runCommandResult(['aws', 'configure', 'get', key, '--profile', profile], false, {
2692
184
  env: process.env,
2693
185
  timeoutMs,
@@ -2702,8 +194,11 @@ const getAwsConfigure = async (key, profile, timeoutMs = AWS_CLI_TIMEOUT_MS) =>
2702
194
  }
2703
195
  return undefined;
2704
196
  };
2705
- const exportCredentials = async (profile, timeoutMs = AWS_CLI_TIMEOUT_MS) => {
197
+ const exportCredentials = async (profile, deadlineMs) => {
2706
198
  const tryExport = async (format) => {
199
+ const timeoutMs = pickTimeoutMs(deadlineMs);
200
+ if (timeoutMs <= 0)
201
+ return undefined;
2707
202
  const argv = [
2708
203
  'aws',
2709
204
  'configure',
@@ -2724,20 +219,13 @@ const exportCredentials = async (profile, timeoutMs = AWS_CLI_TIMEOUT_MS) => {
2724
219
  // Some formats produce JSON ("process"), some produce shell-ish env lines.
2725
220
  return parseExportCredentialsJson(out) ?? parseExportCredentialsEnv(out);
2726
221
  };
2727
- // Prefer the default/JSON "process" format first; then fall back to shell env outputs.
2728
- // Note: AWS CLI v2 supports: process | env | env-no-export | powershell | windows-cmd
2729
- const formats = [
2730
- 'process',
2731
- ...(process.platform === 'win32'
2732
- ? ['powershell', 'windows-cmd', 'env', 'env-no-export']
2733
- : ['env', 'env-no-export']),
2734
- ];
2735
- for (const f of formats) {
2736
- const creds = await tryExport(f);
2737
- if (creds)
2738
- return creds;
2739
- }
2740
- // Final fallback: no --format (AWS CLI default output)
222
+ // Keep the probe set small; budgeted calls above prevent long hangs.
223
+ const primary = await tryExport('process');
224
+ if (primary)
225
+ return primary;
226
+ const secondary = await tryExport(process.platform === 'win32' ? 'powershell' : 'env');
227
+ if (secondary)
228
+ return secondary;
2741
229
  return tryExport(undefined);
2742
230
  };
2743
231
  /**
@@ -2751,6 +239,7 @@ const resolveAwsContext = async ({ dotenv, cfg, }) => {
2751
239
  const profileKey = cfg.profileKey ?? 'AWS_LOCAL_PROFILE';
2752
240
  const profileFallbackKey = cfg.profileFallbackKey ?? 'AWS_PROFILE';
2753
241
  const regionKey = cfg.regionKey ?? 'AWS_REGION';
242
+ const deadlineMs = cfg.strategy !== 'none' ? Date.now() + AWS_CLI_BUDGET_MS : undefined;
2754
243
  const profile = cfg.profile ??
2755
244
  dotenv[profileKey] ??
2756
245
  dotenv[profileFallbackKey] ??
@@ -2760,7 +249,7 @@ const resolveAwsContext = async ({ dotenv, cfg, }) => {
2760
249
  if (cfg.strategy === 'none') {
2761
250
  // If region is still missing and we have a profile, try best-effort region resolve.
2762
251
  if (!region && profile)
2763
- region = await getAwsConfigure('region', profile);
252
+ region = await getAwsConfigure('region', profile, Date.now() + AWS_CLI_BUDGET_MS);
2764
253
  if (!region && cfg.defaultRegion)
2765
254
  region = cfg.defaultRegion;
2766
255
  const out = {};
@@ -2774,12 +263,12 @@ const resolveAwsContext = async ({ dotenv, cfg, }) => {
2774
263
  // Profile wins over ambient env creds when present (from flags/config/dotenv).
2775
264
  if (profile) {
2776
265
  // Try export-credentials
2777
- credentials = await exportCredentials(profile);
266
+ credentials = await exportCredentials(profile, deadlineMs);
2778
267
  // On failure, detect SSO and optionally login then retry
2779
268
  if (!credentials) {
2780
- const ssoSession = await getAwsConfigure('sso_session', profile);
269
+ const ssoSession = await getAwsConfigure('sso_session', profile, deadlineMs);
2781
270
  // Legacy SSO profiles use sso_start_url/sso_region rather than sso_session.
2782
- const ssoStartUrl = await getAwsConfigure('sso_start_url', profile);
271
+ const ssoStartUrl = await getAwsConfigure('sso_start_url', profile, deadlineMs);
2783
272
  const looksSSO = (typeof ssoSession === 'string' && ssoSession.length > 0) ||
2784
273
  (typeof ssoStartUrl === 'string' && ssoStartUrl.length > 0);
2785
274
  if (looksSSO && cfg.loginOnDemand) {
@@ -2791,14 +280,14 @@ const resolveAwsContext = async ({ dotenv, cfg, }) => {
2791
280
  if (exit !== 0) {
2792
281
  throw new Error(`aws sso login failed for profile '${profile}' (exit ${String(exit)})`);
2793
282
  }
2794
- credentials = await exportCredentials(profile);
283
+ credentials = await exportCredentials(profile, deadlineMs);
2795
284
  }
2796
285
  }
2797
286
  // Static fallback if still missing.
2798
287
  if (!credentials) {
2799
- const id = await getAwsConfigure('aws_access_key_id', profile);
2800
- const secret = await getAwsConfigure('aws_secret_access_key', profile);
2801
- const token = await getAwsConfigure('aws_session_token', profile);
288
+ const id = await getAwsConfigure('aws_access_key_id', profile, deadlineMs);
289
+ const secret = await getAwsConfigure('aws_secret_access_key', profile, deadlineMs);
290
+ const token = await getAwsConfigure('aws_session_token', profile, deadlineMs);
2802
291
  if (id && secret) {
2803
292
  credentials = {
2804
293
  accessKeyId: id,
@@ -2823,7 +312,7 @@ const resolveAwsContext = async ({ dotenv, cfg, }) => {
2823
312
  }
2824
313
  // Final region resolution
2825
314
  if (!region && profile)
2826
- region = await getAwsConfigure('region', profile);
315
+ region = await getAwsConfigure('region', profile, deadlineMs);
2827
316
  if (!region && cfg.defaultRegion)
2828
317
  region = cfg.defaultRegion;
2829
318
  const out = {};
@@ -2988,7 +477,7 @@ function attachAwsDefaultAction(cli, plugin, awsCmd) {
2988
477
  * @internal
2989
478
  */
2990
479
  function attachAwsOptions(cli, plugin) {
2991
- return (cli
480
+ return cli
2992
481
  // Description is owned by the plugin index (src/plugins/aws/index.ts).
2993
482
  .enablePositionalOptions()
2994
483
  .passThroughOptions()
@@ -3006,7 +495,7 @@ function attachAwsOptions(cli, plugin) {
3006
495
  .addOption(plugin.createPluginDynamicOption(cli, '--profile-fallback-key <string>', (_bag, cfg) => `fallback dotenv/config key for profile${cfg.profileFallbackKey ? ` (default: ${JSON.stringify(cfg.profileFallbackKey)})` : ''}`))
3007
496
  .addOption(plugin.createPluginDynamicOption(cli, '--region-key <string>', (_bag, cfg) => `dotenv/config key for region${cfg.regionKey ? ` (default: ${JSON.stringify(cfg.regionKey)})` : ''}`))
3008
497
  // Accept any extra operands so Commander does not error when tokens appear after "--".
3009
- .argument('[args...]'));
498
+ .argument('[args...]');
3010
499
  }
3011
500
 
3012
501
  /**
@@ -3060,8 +549,16 @@ const awsPluginConfigSchema = z.object({
3060
549
  profileFallbackKey: z.string().default('AWS_PROFILE').optional(),
3061
550
  /** Dotenv/config key for region lookup (default `AWS_REGION`). */
3062
551
  regionKey: z.string().default('AWS_REGION').optional(),
3063
- /** Credential acquisition strategy (`cli-export` to resolve via AWS CLI, or `none` to skip). */
3064
- strategy: z.enum(['cli-export', 'none']).default('cli-export').optional(),
552
+ /**
553
+ * Credential acquisition strategy.
554
+ *
555
+ * - `'cli-export'`: resolve via AWS CLI
556
+ * - `'none'`: skip credential resolution
557
+ */
558
+ strategy: z
559
+ .union([z.literal('cli-export'), z.literal('none')])
560
+ .default('cli-export')
561
+ .optional(),
3065
562
  /** When true, attempt `aws sso login` on-demand when credential export fails for an SSO profile. */
3066
563
  loginOnDemand: z.boolean().default(false).optional(),
3067
564
  });