@karmaniverous/get-dotenv 5.2.6 → 6.0.0-1

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 (55) hide show
  1. package/README.md +106 -70
  2. package/dist/cliHost.d.ts +232 -226
  3. package/dist/cliHost.mjs +777 -545
  4. package/dist/config.d.ts +7 -2
  5. package/dist/env-overlay.d.ts +21 -9
  6. package/dist/env-overlay.mjs +14 -19
  7. package/dist/getdotenv.cli.mjs +1366 -1163
  8. package/dist/index.d.ts +415 -242
  9. package/dist/index.mjs +1364 -1414
  10. package/dist/plugins-aws.d.ts +149 -94
  11. package/dist/plugins-aws.mjs +307 -195
  12. package/dist/plugins-batch.d.ts +153 -99
  13. package/dist/plugins-batch.mjs +277 -95
  14. package/dist/plugins-cmd.d.ts +140 -94
  15. package/dist/plugins-cmd.mjs +636 -502
  16. package/dist/plugins-demo.d.ts +140 -94
  17. package/dist/plugins-demo.mjs +237 -46
  18. package/dist/plugins-init.d.ts +140 -94
  19. package/dist/plugins-init.mjs +129 -12
  20. package/dist/plugins.d.ts +166 -103
  21. package/dist/plugins.mjs +977 -840
  22. package/package.json +15 -53
  23. package/templates/cli/ts/plugins/hello.ts +27 -6
  24. package/templates/config/js/getdotenv.config.js +1 -1
  25. package/templates/config/ts/getdotenv.config.ts +9 -2
  26. package/dist/cliHost.cjs +0 -1875
  27. package/dist/cliHost.d.cts +0 -409
  28. package/dist/cliHost.d.mts +0 -409
  29. package/dist/config.cjs +0 -252
  30. package/dist/config.d.cts +0 -55
  31. package/dist/config.d.mts +0 -55
  32. package/dist/env-overlay.cjs +0 -163
  33. package/dist/env-overlay.d.cts +0 -50
  34. package/dist/env-overlay.d.mts +0 -50
  35. package/dist/index.cjs +0 -4140
  36. package/dist/index.d.cts +0 -457
  37. package/dist/index.d.mts +0 -457
  38. package/dist/plugins-aws.cjs +0 -667
  39. package/dist/plugins-aws.d.cts +0 -158
  40. package/dist/plugins-aws.d.mts +0 -158
  41. package/dist/plugins-batch.cjs +0 -616
  42. package/dist/plugins-batch.d.cts +0 -180
  43. package/dist/plugins-batch.d.mts +0 -180
  44. package/dist/plugins-cmd.cjs +0 -1113
  45. package/dist/plugins-cmd.d.cts +0 -178
  46. package/dist/plugins-cmd.d.mts +0 -178
  47. package/dist/plugins-demo.cjs +0 -307
  48. package/dist/plugins-demo.d.cts +0 -158
  49. package/dist/plugins-demo.d.mts +0 -158
  50. package/dist/plugins-init.cjs +0 -289
  51. package/dist/plugins-init.d.cts +0 -162
  52. package/dist/plugins-init.d.mts +0 -162
  53. package/dist/plugins.cjs +0 -2283
  54. package/dist/plugins.d.cts +0 -210
  55. package/dist/plugins.d.mts +0 -210
package/dist/cliHost.cjs DELETED
@@ -1,1875 +0,0 @@
1
- 'use strict';
2
-
3
- var commander = require('commander');
4
- var fs = require('fs-extra');
5
- var packageDirectory = require('package-directory');
6
- var path = require('path');
7
- var url = require('url');
8
- var YAML = require('yaml');
9
- var zod = require('zod');
10
- var nanoid = require('nanoid');
11
- var dotenv = require('dotenv');
12
- var crypto = require('crypto');
13
-
14
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
- /**
16
- * Dotenv expansion utilities.
17
- *
18
- * This module implements recursive expansion of environment-variable
19
- * references in strings and records. It supports both whitespace and
20
- * bracket syntaxes with optional defaults:
21
- *
22
- * - Whitespace: `$VAR[:default]`
23
- * - Bracketed: `${VAR[:default]}`
24
- *
25
- * Escaped dollar signs (`\$`) are preserved.
26
- * Unknown variables resolve to empty string unless a default is provided.
27
- */
28
- /**
29
- * Like String.prototype.search but returns the last index.
30
- * @internal
31
- */
32
- const searchLast = (str, rgx) => {
33
- const matches = Array.from(str.matchAll(rgx));
34
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
35
- };
36
- const replaceMatch = (value, match, ref) => {
37
- /**
38
- * @internal
39
- */
40
- const group = match[0];
41
- const key = match[1];
42
- const defaultValue = match[2];
43
- if (!key)
44
- return value;
45
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
46
- return interpolate(replacement, ref);
47
- };
48
- const interpolate = (value = '', ref = {}) => {
49
- /**
50
- * @internal
51
- */
52
- // if value is falsy, return it as is
53
- if (!value)
54
- return value;
55
- // get position of last unescaped dollar sign
56
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
57
- // return value if none found
58
- if (lastUnescapedDollarSignIndex === -1)
59
- return value;
60
- // evaluate the value tail
61
- const tail = value.slice(lastUnescapedDollarSignIndex);
62
- // find whitespace pattern: $KEY:DEFAULT
63
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
64
- const whitespaceMatch = whitespacePattern.exec(tail);
65
- if (whitespaceMatch != null)
66
- return replaceMatch(value, whitespaceMatch, ref);
67
- else {
68
- // find bracket pattern: ${KEY:DEFAULT}
69
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
70
- const bracketMatch = bracketPattern.exec(tail);
71
- if (bracketMatch != null)
72
- return replaceMatch(value, bracketMatch, ref);
73
- }
74
- return value;
75
- };
76
- /**
77
- * Recursively expands environment variables in a string. Variables may be
78
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
79
- * Unknown variables will expand to an empty string.
80
- *
81
- * @param value - The string to expand.
82
- * @param ref - The reference object to use for variable expansion.
83
- * @returns The expanded string.
84
- *
85
- * @example
86
- * ```ts
87
- * process.env.FOO = 'bar';
88
- * dotenvExpand('Hello $FOO'); // "Hello bar"
89
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
90
- * ```
91
- *
92
- * @remarks
93
- * The expansion is recursive. If a referenced variable itself contains
94
- * references, those will also be expanded until a stable value is reached.
95
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
96
- */
97
- const dotenvExpand = (value, ref = process.env) => {
98
- const result = interpolate(value, ref);
99
- return result ? result.replace(/\\\$/g, '$') : undefined;
100
- };
101
- /**
102
- * Recursively expands environment variables in the values of a JSON object.
103
- * Variables may be presented with optional default as `$VAR[:default]` or
104
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
105
- *
106
- * @param values - The values object to expand.
107
- * @param options - Expansion options.
108
- * @returns The value object with expanded string values.
109
- *
110
- * @example
111
- * ```ts
112
- * process.env.FOO = 'bar';
113
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
114
- * // => { A: "bar", B: "xbary" }
115
- * ```
116
- *
117
- * @remarks
118
- * Options:
119
- * - ref: The reference object to use for expansion (defaults to process.env).
120
- * - progressive: Whether to progressively add expanded values to the set of
121
- * reference keys.
122
- *
123
- * When `progressive` is true, each expanded key becomes available for
124
- * subsequent expansions in the same object (left-to-right by object key order).
125
- */
126
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
127
- const { ref = process.env, progressive = false } = options;
128
- acc[key] = dotenvExpand(values[key], {
129
- ...ref,
130
- ...(progressive ? acc : {}),
131
- });
132
- return acc;
133
- }, {});
134
- /**
135
- * Recursively expands environment variables in a string using `process.env` as
136
- * the expansion reference. Variables may be presented with optional default as
137
- * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
138
- * empty string.
139
- *
140
- * @param value - The string to expand.
141
- * @returns The expanded string.
142
- *
143
- * @example
144
- * ```ts
145
- * process.env.FOO = 'bar';
146
- * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
147
- * ```
148
- */
149
- const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
150
-
151
- /**
152
- * Attach legacy root flags to a Commander program.
153
- * Uses provided defaults to render help labels without coupling to generators.
154
- */
155
- const attachRootOptions = (program, defaults, opts) => {
156
- // Install temporary wrappers to tag all options added here as "base".
157
- const GROUP = 'base';
158
- const tagLatest = (cmd, group) => {
159
- const optsArr = cmd.options;
160
- if (Array.isArray(optsArr) && optsArr.length > 0) {
161
- const last = optsArr[optsArr.length - 1];
162
- last.__group = group;
163
- }
164
- };
165
- const originalAddOption = program.addOption.bind(program);
166
- const originalOption = program.option.bind(program);
167
- program.addOption = function patchedAdd(opt) {
168
- // Tag before adding, in case consumers inspect the Option directly.
169
- opt.__group = GROUP;
170
- const ret = originalAddOption(opt);
171
- return ret;
172
- };
173
- program.option = function patchedOption(...args) {
174
- const ret = originalOption(...args);
175
- tagLatest(this, GROUP);
176
- return ret;
177
- };
178
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
179
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
180
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
181
- // Build initial chain.
182
- let p = program
183
- .enablePositionalOptions()
184
- .passThroughOptions()
185
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
186
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
187
- ['KEY1', 'VAL1'],
188
- ['KEY2', 'VAL2'],
189
- ]
190
- .map((v) => v.join(va))
191
- .join(vd)}`, dotenvExpandFromProcessEnv);
192
- // Optional legacy root command flag (kept for generated CLI compatibility).
193
- // Default is OFF; the generator opts in explicitly.
194
- if (opts?.includeCommandOption === true) {
195
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
196
- }
197
- p = p
198
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
199
- .addOption(new commander.Option('-s, --shell [string]', (() => {
200
- let defaultLabel = '';
201
- if (shell !== undefined) {
202
- if (typeof shell === 'boolean') {
203
- defaultLabel = ' (default OS shell)';
204
- }
205
- else if (typeof shell === 'string') {
206
- // Safe string interpolation
207
- defaultLabel = ` (default ${shell})`;
208
- }
209
- }
210
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
211
- })()).conflicts('shellOff'))
212
- .addOption(new commander.Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
213
- .addOption(new commander.Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
214
- .addOption(new commander.Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
215
- .addOption(new commander.Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
216
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
217
- ? ' (default)'
218
- : ''}`).conflicts('excludeAllOff'))
219
- .addOption(new commander.Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
220
- .addOption(new commander.Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
221
- .addOption(new commander.Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
222
- .addOption(new commander.Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
223
- .addOption(new commander.Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
224
- .addOption(new commander.Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
225
- .addOption(new commander.Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
226
- .addOption(new commander.Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
227
- .addOption(new commander.Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
228
- .addOption(new commander.Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
229
- .addOption(new commander.Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
230
- .addOption(new commander.Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
231
- .addOption(new commander.Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
232
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
233
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
234
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
235
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
236
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
237
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
238
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
239
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
240
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
241
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
242
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
243
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
244
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
245
- // Hidden scripts pipe-through (stringified)
246
- .addOption(new commander.Option('--scripts <string>')
247
- .default(JSON.stringify(scripts))
248
- .hideHelp());
249
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
250
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
251
- // Validation: strict mode fails on env validation issues (warn by default).
252
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
253
- // Entropy diagnostics (presentation-only)
254
- p = p
255
- .addOption(new commander.Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
256
- .addOption(new commander.Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
257
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
258
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
259
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
260
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
261
- // Restore original methods to avoid tagging future additions outside base.
262
- program.addOption = originalAddOption;
263
- program.option = originalOption;
264
- return p;
265
- };
266
-
267
- // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
268
- const baseRootOptionDefaults = {
269
- dotenvToken: '.env',
270
- loadProcess: true,
271
- logger: console,
272
- // Diagnostics defaults
273
- warnEntropy: true,
274
- entropyThreshold: 3.8,
275
- entropyMinLength: 16,
276
- entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
277
- paths: './',
278
- pathsDelimiter: ' ',
279
- privateToken: 'local',
280
- scripts: {
281
- 'git-status': {
282
- cmd: 'git branch --show-current && git status -s -u',
283
- shell: true,
284
- },
285
- },
286
- shell: true,
287
- vars: '',
288
- varsAssignor: '=',
289
- varsDelimiter: ' ',
290
- // tri-state flags default to unset unless explicitly provided
291
- // (debug/log/exclude* resolved via flag utils)
292
- };
293
-
294
- /** @internal */
295
- const isPlainObject$1 = (value) => value !== null &&
296
- typeof value === 'object' &&
297
- Object.getPrototypeOf(value) === Object.prototype;
298
- const mergeInto = (target, source) => {
299
- for (const [key, sVal] of Object.entries(source)) {
300
- if (sVal === undefined)
301
- continue; // do not overwrite with undefined
302
- const tVal = target[key];
303
- if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
304
- target[key] = mergeInto({ ...tVal }, sVal);
305
- }
306
- else if (isPlainObject$1(sVal)) {
307
- target[key] = mergeInto({}, sVal);
308
- }
309
- else {
310
- target[key] = sVal;
311
- }
312
- }
313
- return target;
314
- };
315
- /**
316
- * Perform a deep defaults-style merge across plain objects. *
317
- * - Only merges plain objects (prototype === Object.prototype).
318
- * - Arrays and non-objects are replaced, not merged.
319
- * - `undefined` values are ignored and do not overwrite prior values.
320
- *
321
- * @typeParam T - The resulting shape after merging all layers.
322
- * @param layers - Zero or more partial layers in ascending precedence order.
323
- * @returns The merged object typed as {@link T}.
324
- *
325
- * @example
326
- * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
327
- * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
328
- */
329
- const defaultsDeep = (...layers) => {
330
- const result = layers
331
- .filter(Boolean)
332
- .reduce((acc, layer) => mergeInto(acc, layer), {});
333
- return result;
334
- };
335
-
336
- /**
337
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
338
- * - If the user explicitly enabled the flag, return true.
339
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
340
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
341
- *
342
- * @param exclude - The "on" flag value as parsed by Commander.
343
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
344
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
345
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
346
- *
347
- * @example
348
- * ```ts
349
- * resolveExclusion(undefined, undefined, true); // => true
350
- * ```
351
- */
352
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
353
- /**
354
- * Resolve an optional flag with "--exclude-all" overrides.
355
- * If excludeAll is set and the individual "...-off" is not, force true.
356
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
357
- * Otherwise, adopt the default (true → set; false/undefined → unset).
358
- *
359
- * @param exclude - Individual include/exclude flag.
360
- * @param excludeOff - Individual "...-off" flag.
361
- * @param defaultValue - Default for the individual flag.
362
- * @param excludeAll - Global "exclude-all" flag.
363
- * @param excludeAllOff - Global "exclude-all-off" flag.
364
- *
365
- * @example
366
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
367
- */
368
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
369
- // Order of precedence:
370
- // 1) Individual explicit "on" wins outright.
371
- // 2) Individual explicit "off" wins over any global.
372
- // 3) Global exclude-all forces true when not explicitly turned off.
373
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
374
- // 5) Fall back to the default (true => set; false/undefined => unset).
375
- (() => {
376
- // Individual "on"
377
- if (exclude === true)
378
- return true;
379
- // Individual "off"
380
- if (excludeOff === true)
381
- return undefined;
382
- // Global "exclude-all" ON (unless explicitly turned off)
383
- if (excludeAll === true)
384
- return true;
385
- // Global "exclude-all-off" (unless explicitly enabled)
386
- if (excludeAllOff === true)
387
- return undefined;
388
- // Default
389
- return defaultValue ? true : undefined;
390
- })();
391
- /**
392
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
393
- * delete when undefined; assign when defined — without requiring an index signature on T.
394
- *
395
- * @typeParam T - Target object type.
396
- * @param obj - The object to write to.
397
- * @param key - The optional boolean property key of {@link T}.
398
- * @param value - The value to set or `undefined` to unset.
399
- *
400
- * @remarks
401
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
402
- */
403
- const setOptionalFlag = (obj, key, value) => {
404
- const target = obj;
405
- const k = key;
406
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
407
- if (value === undefined)
408
- delete target[k];
409
- else
410
- target[k] = value;
411
- };
412
-
413
- /**
414
- * Merge and normalize raw Commander options (current + parent + defaults)
415
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
416
- * avoid cross-layer coupling; callers may cast as needed.
417
- */
418
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
419
- const parent = typeof parentJson === 'string' && parentJson.length > 0
420
- ? JSON.parse(parentJson)
421
- : undefined;
422
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
423
- const current = { ...rest };
424
- if (typeof scripts === 'string') {
425
- try {
426
- current.scripts = JSON.parse(scripts);
427
- }
428
- catch {
429
- // ignore parse errors; leave scripts undefined
430
- }
431
- }
432
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
433
- const d = defaults;
434
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
435
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
436
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
437
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
438
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
439
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
440
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
441
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
442
- // warnEntropy (tri-state)
443
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
444
- // Normalize shell for predictability: explicit default shell per OS.
445
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
446
- let resolvedShell = merged.shell;
447
- if (shellOff)
448
- resolvedShell = false;
449
- else if (resolvedShell === true || resolvedShell === undefined) {
450
- resolvedShell = defaultShell;
451
- }
452
- else if (typeof resolvedShell !== 'string' &&
453
- typeof defaults.shell === 'string') {
454
- resolvedShell = defaults.shell;
455
- }
456
- merged.shell = resolvedShell;
457
- const cmd = typeof command === 'string' ? command : undefined;
458
- return cmd !== undefined ? { merged, command: cmd } : { merged };
459
- };
460
-
461
- /**
462
- * Zod schemas for configuration files discovered by the new loader.
463
- *
464
- * Notes:
465
- * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
466
- * - RESOLVED: normalized shapes (paths always string[]).
467
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
468
- */
469
- // String-only env value map
470
- const stringMap = zod.z.record(zod.z.string(), zod.z.string());
471
- const envStringMap = zod.z.record(zod.z.string(), stringMap);
472
- // Allow string[] or single string for "paths" in RAW; normalize later.
473
- const rawPathsSchema = zod.z.union([zod.z.array(zod.z.string()), zod.z.string()]).optional();
474
- const getDotenvConfigSchemaRaw = zod.z.object({
475
- dotenvToken: zod.z.string().optional(),
476
- privateToken: zod.z.string().optional(),
477
- paths: rawPathsSchema,
478
- loadProcess: zod.z.boolean().optional(),
479
- log: zod.z.boolean().optional(),
480
- shell: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
481
- scripts: zod.z.record(zod.z.string(), zod.z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
482
- requiredKeys: zod.z.array(zod.z.string()).optional(),
483
- schema: zod.z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
484
- vars: stringMap.optional(), // public, global
485
- envVars: envStringMap.optional(), // public, per-env
486
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
487
- dynamic: zod.z.unknown().optional(),
488
- // Per-plugin config bag; validated by plugins/host when used.
489
- plugins: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
490
- });
491
- // Normalize paths to string[]
492
- const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
493
- const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
494
- ...raw,
495
- paths: normalizePaths(raw.paths),
496
- }));
497
-
498
- // Discovery candidates (first match wins per scope/privacy).
499
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
500
- const PUBLIC_FILENAMES = [
501
- 'getdotenv.config.json',
502
- 'getdotenv.config.yaml',
503
- 'getdotenv.config.yml',
504
- 'getdotenv.config.js',
505
- 'getdotenv.config.mjs',
506
- 'getdotenv.config.cjs',
507
- 'getdotenv.config.ts',
508
- 'getdotenv.config.mts',
509
- 'getdotenv.config.cts',
510
- ];
511
- const LOCAL_FILENAMES = [
512
- 'getdotenv.config.local.json',
513
- 'getdotenv.config.local.yaml',
514
- 'getdotenv.config.local.yml',
515
- 'getdotenv.config.local.js',
516
- 'getdotenv.config.local.mjs',
517
- 'getdotenv.config.local.cjs',
518
- 'getdotenv.config.local.ts',
519
- 'getdotenv.config.local.mts',
520
- 'getdotenv.config.local.cts',
521
- ];
522
- const isYaml = (p) => ['.yaml', '.yml'].includes(path.extname(p).toLowerCase());
523
- const isJson = (p) => path.extname(p).toLowerCase() === '.json';
524
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(path.extname(p).toLowerCase());
525
- // --- Internal JS/TS module loader helpers (default export) ---
526
- const importDefault$1 = async (fileUrl) => {
527
- const mod = (await import(fileUrl));
528
- return mod.default;
529
- };
530
- const cacheName = (absPath, suffix) => {
531
- // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
532
- const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
533
- return `${base}.${suffix}.mjs`;
534
- };
535
- const ensureDir = async (dir) => {
536
- await fs.ensureDir(dir);
537
- return dir;
538
- };
539
- const loadJsTsDefault = async (absPath) => {
540
- const fileUrl = url.pathToFileURL(absPath).toString();
541
- const ext = path.extname(absPath).toLowerCase();
542
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
543
- return importDefault$1(fileUrl);
544
- }
545
- // Try direct import first in case a TS loader is active.
546
- try {
547
- const val = await importDefault$1(fileUrl);
548
- if (val)
549
- return val;
550
- }
551
- catch {
552
- /* fallthrough */
553
- }
554
- // esbuild bundle to a temp ESM file
555
- try {
556
- const esbuild = (await import('esbuild'));
557
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
558
- const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
559
- await esbuild.build({
560
- entryPoints: [absPath],
561
- bundle: true,
562
- platform: 'node',
563
- format: 'esm',
564
- target: 'node20',
565
- outfile,
566
- sourcemap: false,
567
- logLevel: 'silent',
568
- });
569
- return await importDefault$1(url.pathToFileURL(outfile).toString());
570
- }
571
- catch {
572
- /* fallthrough to TS transpile */
573
- }
574
- // typescript.transpileModule simple transpile (single-file)
575
- try {
576
- const ts = (await import('typescript'));
577
- const src = await fs.readFile(absPath, 'utf-8');
578
- const out = ts.transpileModule(src, {
579
- compilerOptions: {
580
- module: 'ESNext',
581
- target: 'ES2022',
582
- moduleResolution: 'NodeNext',
583
- },
584
- }).outputText;
585
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
586
- const outfile = path.join(outDir, cacheName(absPath, 'ts'));
587
- await fs.writeFile(outfile, out, 'utf-8');
588
- return await importDefault$1(url.pathToFileURL(outfile).toString());
589
- }
590
- catch {
591
- throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
592
- }
593
- };
594
- /**
595
- * Discover JSON/YAML config files in the packaged root and project root.
596
- * Order: packaged public → project public → project local. */
597
- const discoverConfigFiles = async (importMetaUrl) => {
598
- const files = [];
599
- // Packaged root via importMetaUrl (optional)
600
- if (importMetaUrl) {
601
- const fromUrl = url.fileURLToPath(importMetaUrl);
602
- const packagedRoot = await packageDirectory.packageDirectory({ cwd: fromUrl });
603
- if (packagedRoot) {
604
- for (const name of PUBLIC_FILENAMES) {
605
- const p = path.join(packagedRoot, name);
606
- if (await fs.pathExists(p)) {
607
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
608
- break; // only one public file expected per scope
609
- }
610
- }
611
- // By policy, packaged .local is not expected; skip even if present.
612
- }
613
- }
614
- // Project root (from current working directory)
615
- const projectRoot = await packageDirectory.packageDirectory();
616
- if (projectRoot) {
617
- for (const name of PUBLIC_FILENAMES) {
618
- const p = path.join(projectRoot, name);
619
- if (await fs.pathExists(p)) {
620
- files.push({ path: p, privacy: 'public', scope: 'project' });
621
- break;
622
- }
623
- }
624
- for (const name of LOCAL_FILENAMES) {
625
- const p = path.join(projectRoot, name);
626
- if (await fs.pathExists(p)) {
627
- files.push({ path: p, privacy: 'local', scope: 'project' });
628
- break;
629
- }
630
- }
631
- }
632
- return files;
633
- };
634
- /**
635
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
636
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
637
- *
638
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
639
- * For JS/TS: default export is loaded; "dynamic" is allowed.
640
- */
641
- const loadConfigFile = async (filePath) => {
642
- let raw = {};
643
- try {
644
- const abs = path.resolve(filePath);
645
- if (isJsOrTs(abs)) {
646
- // JS/TS support: load default export via robust pipeline.
647
- const mod = await loadJsTsDefault(abs);
648
- raw = mod ?? {};
649
- }
650
- else {
651
- const txt = await fs.readFile(abs, 'utf-8');
652
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
653
- }
654
- }
655
- catch (err) {
656
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
657
- }
658
- // Validate RAW
659
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
660
- if (!parsed.success) {
661
- const msgs = parsed.error.issues
662
- .map((i) => `${i.path.join('.')}: ${i.message}`)
663
- .join('\n');
664
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
665
- }
666
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
667
- if (!isJsOrTs(filePath) &&
668
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
669
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
670
- `Use JS/TS config for "dynamic" or "schema".`);
671
- }
672
- return getDotenvConfigSchemaResolved.parse(parsed.data);
673
- };
674
- /**
675
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
676
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
677
- */
678
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
679
- const discovered = await discoverConfigFiles(importMetaUrl);
680
- const result = {};
681
- for (const f of discovered) {
682
- const cfg = await loadConfigFile(f.path);
683
- if (f.scope === 'packaged') {
684
- // packaged public only
685
- result.packaged = cfg;
686
- }
687
- else {
688
- result.project ??= {};
689
- if (f.privacy === 'public')
690
- result.project.public = cfg;
691
- else
692
- result.project.local = cfg;
693
- }
694
- }
695
- return result;
696
- };
697
-
698
- /**
699
- * Validate a composed env against config-provided validation surfaces.
700
- * Precedence for validation definitions:
701
- * project.local -\> project.public -\> packaged
702
- *
703
- * Behavior:
704
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
705
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
706
- * - Returns a flat list of issue strings; caller decides warn vs fail.
707
- */
708
- const validateEnvAgainstSources = (finalEnv, sources) => {
709
- const pick = (getter) => {
710
- const pl = sources.project?.local;
711
- const pp = sources.project?.public;
712
- const pk = sources.packaged;
713
- return ((pl && getter(pl)) ||
714
- (pp && getter(pp)) ||
715
- (pk && getter(pk)) ||
716
- undefined);
717
- };
718
- const schema = pick((cfg) => cfg['schema']);
719
- if (schema &&
720
- typeof schema.safeParse === 'function') {
721
- try {
722
- const parsed = schema.safeParse(finalEnv);
723
- if (!parsed.success) {
724
- // Try to render zod-style issues when available.
725
- const err = parsed.error;
726
- const issues = Array.isArray(err.issues) && err.issues.length > 0
727
- ? err.issues.map((i) => {
728
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
729
- const msg = i.message ?? 'Invalid value';
730
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
731
- })
732
- : ['[schema] validation failed'];
733
- return issues;
734
- }
735
- return [];
736
- }
737
- catch {
738
- // If schema invocation fails, surface a single diagnostic.
739
- return [
740
- '[schema] validation failed (unable to execute schema.safeParse)',
741
- ];
742
- }
743
- }
744
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
745
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
746
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
747
- if (missing.length > 0) {
748
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
749
- }
750
- }
751
- return [];
752
- };
753
-
754
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
755
-
756
- // src/GetDotenvOptions.ts
757
- const getDotenvOptionsFilename = 'getdotenv.config.json';
758
- /**
759
- * Converts programmatic CLI options to `getDotenv` options. *
760
- * @param cliOptions - CLI options. Defaults to `{}`.
761
- *
762
- * @returns `getDotenv` options.
763
- */
764
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
765
- /**
766
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
767
- *
768
- * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
769
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
770
- * - Drops CLI-only keys that have no programmatic equivalent.
771
- *
772
- * @remarks
773
- * Follows exact-optional semantics by not emitting undefined-valued entries.
774
- */
775
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
776
- // Create a shallow copy then delete optional CLI-only keys if present.
777
- const restObj = { ...rest };
778
- delete restObj.debug;
779
- delete restObj.scripts;
780
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
781
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
782
- let parsedVars;
783
- if (typeof vars === 'string') {
784
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
785
- ? RegExp(varsAssignorPattern)
786
- : (varsAssignor ?? '=')));
787
- parsedVars = Object.fromEntries(kvPairs);
788
- }
789
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
790
- // Keep only string or undefined values to match ProcessEnv.
791
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
792
- parsedVars = Object.fromEntries(entries);
793
- }
794
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
795
- // expectations and the compat test assertions.
796
- if (parsedVars) {
797
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
798
- }
799
- // Tolerate paths as either a delimited string or string[]
800
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
801
- // under the RootOptionsShape (which declares paths as string | undefined).
802
- const pathsAny = paths;
803
- const pathsOut = Array.isArray(pathsAny)
804
- ? pathsAny.filter((p) => typeof p === 'string')
805
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
806
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
807
- return {
808
- ...restObj,
809
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
810
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
811
- };
812
- };
813
- const resolveGetDotenvOptions = async (customOptions) => {
814
- /**
815
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
816
- *
817
- * 1. Base defaults derived from the CLI generator defaults
818
- * ({@link baseGetDotenvCliOptions}).
819
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
820
- * package root (if present).
821
- * 3. The provided {@link customOptions}.
822
- *
823
- * The result preserves explicit empty values and drops only `undefined`.
824
- *
825
- * @returns Fully-resolved {@link GetDotenvOptions}.
826
- *
827
- * @example
828
- * ```ts
829
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
830
- * ```
831
- */
832
- const localPkgDir = await packageDirectory.packageDirectory();
833
- const localOptionsPath = localPkgDir
834
- ? path.join(localPkgDir, getDotenvOptionsFilename)
835
- : undefined;
836
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
837
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
838
- : {});
839
- // Merge order: base < local < custom (custom has highest precedence)
840
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
841
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
842
- const result = defaultsDeep(defaultsFromCli, customOptions);
843
- return {
844
- ...result, // Keep explicit empty strings/zeros; drop only undefined
845
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
846
- };
847
- };
848
-
849
- /**
850
- * Zod schemas for programmatic GetDotenv options.
851
- *
852
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
853
- * Legacy paths continue to use existing types/logic. The new plugin host will
854
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
855
- * later per the staged plan.
856
- */
857
- // Minimal process env representation: string values or undefined to indicate "unset".
858
- const processEnvSchema = zod.z.record(zod.z.string(), zod.z.string().optional());
859
- // RAW: all fields optional — undefined means "inherit" from lower layers.
860
- const getDotenvOptionsSchemaRaw = zod.z.object({
861
- defaultEnv: zod.z.string().optional(),
862
- dotenvToken: zod.z.string().optional(),
863
- dynamicPath: zod.z.string().optional(),
864
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
865
- dynamic: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
866
- env: zod.z.string().optional(),
867
- excludeDynamic: zod.z.boolean().optional(),
868
- excludeEnv: zod.z.boolean().optional(),
869
- excludeGlobal: zod.z.boolean().optional(),
870
- excludePrivate: zod.z.boolean().optional(),
871
- excludePublic: zod.z.boolean().optional(),
872
- loadProcess: zod.z.boolean().optional(),
873
- log: zod.z.boolean().optional(),
874
- outputPath: zod.z.string().optional(),
875
- paths: zod.z.array(zod.z.string()).optional(),
876
- privateToken: zod.z.string().optional(),
877
- vars: processEnvSchema.optional(),
878
- // Host-only feature flag: guarded integration of config loader/overlay
879
- useConfigLoader: zod.z.boolean().optional(),
880
- });
881
- // RESOLVED: service-boundary contract (post-inheritance).
882
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
883
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
884
-
885
- const applyKv = (current, kv) => {
886
- if (!kv || Object.keys(kv).length === 0)
887
- return current;
888
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
889
- return { ...current, ...expanded };
890
- };
891
- const applyConfigSlice = (current, cfg, env) => {
892
- if (!cfg)
893
- return current;
894
- // kind axis: global then env (env overrides global)
895
- const afterGlobal = applyKv(current, cfg.vars);
896
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
897
- return applyKv(afterGlobal, envKv);
898
- };
899
- /**
900
- * Overlay config-provided values onto a base ProcessEnv using precedence axes:
901
- * - kind: env \> global
902
- * - privacy: local \> public
903
- * - source: project \> packaged \> base
904
- *
905
- * Programmatic explicit vars (if provided) override all config slices.
906
- * Progressive expansion is applied within each slice.
907
- */
908
- const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
909
- let current = { ...base };
910
- // Source: packaged (public -> local)
911
- current = applyConfigSlice(current, configs.packaged, env);
912
- // Packaged "local" is not expected by policy; if present, honor it.
913
- // We do not have a separate object for packaged.local in sources, keep as-is.
914
- // Source: project (public -> local)
915
- current = applyConfigSlice(current, configs.project?.public, env);
916
- current = applyConfigSlice(current, configs.project?.local, env);
917
- // Programmatic explicit vars (top of static tier)
918
- if (programmaticVars) {
919
- const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
920
- current = applyKv(current, toApply);
921
- }
922
- return current;
923
- };
924
-
925
- /** src/diagnostics/entropy.ts
926
- * Entropy diagnostics (presentation-only).
927
- * - Gated by min length and printable ASCII.
928
- * - Warn once per key per run when bits/char \>= threshold.
929
- * - Supports whitelist patterns to suppress known-noise keys.
930
- */
931
- const warned = new Set();
932
- const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
933
- const compile$1 = (patterns) => (patterns ?? []).map((p) => new RegExp(p, 'i'));
934
- const whitelisted = (key, regs) => regs.some((re) => re.test(key));
935
- const shannonBitsPerChar = (s) => {
936
- const freq = new Map();
937
- for (const ch of s)
938
- freq.set(ch, (freq.get(ch) ?? 0) + 1);
939
- const n = s.length;
940
- let h = 0;
941
- for (const c of freq.values()) {
942
- const p = c / n;
943
- h -= p * Math.log2(p);
944
- }
945
- return h;
946
- };
947
- /**
948
- * Maybe emit a one-line entropy warning for a key.
949
- * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
950
- */
951
- const maybeWarnEntropy = (key, value, origin, opts, emit) => {
952
- if (!opts || opts.warnEntropy === false)
953
- return;
954
- if (warned.has(key))
955
- return;
956
- const v = value ?? '';
957
- const minLen = Math.max(0, opts.entropyMinLength ?? 16);
958
- const threshold = opts.entropyThreshold ?? 3.8;
959
- if (v.length < minLen)
960
- return;
961
- if (!isPrintableAscii(v))
962
- return;
963
- const wl = compile$1(opts.entropyWhitelist);
964
- if (whitelisted(key, wl))
965
- return;
966
- const bpc = shannonBitsPerChar(v);
967
- if (bpc >= threshold) {
968
- warned.add(key);
969
- emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
970
- }
971
- };
972
-
973
- const DEFAULT_PATTERNS = [
974
- '\\bsecret\\b',
975
- '\\btoken\\b',
976
- '\\bpass(word)?\\b',
977
- '\\bapi[_-]?key\\b',
978
- '\\bkey\\b',
979
- ];
980
- const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
981
- const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
982
- const MASK = '[redacted]';
983
- /**
984
- * Produce a shallow redacted copy of an env-like object for display.
985
- */
986
- const redactObject = (obj, opts) => {
987
- if (!opts?.redact)
988
- return { ...obj };
989
- const regs = compile(opts.redactPatterns);
990
- const out = {};
991
- for (const [k, v] of Object.entries(obj)) {
992
- out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
993
- }
994
- return out;
995
- };
996
-
997
- /**
998
- * Asynchronously read a dotenv file & parse it into an object.
999
- *
1000
- * @param path - Path to dotenv file.
1001
- * @returns The parsed dotenv object.
1002
- */
1003
- const readDotenv = async (path) => {
1004
- try {
1005
- return (await fs.exists(path)) ? dotenv.parse(await fs.readFile(path)) : {};
1006
- }
1007
- catch {
1008
- return {};
1009
- }
1010
- };
1011
-
1012
- const importDefault = async (fileUrl) => {
1013
- const mod = (await import(fileUrl));
1014
- return mod.default;
1015
- };
1016
- const cacheHash = (absPath, mtimeMs) => crypto.createHash('sha1')
1017
- .update(absPath)
1018
- .update(String(mtimeMs))
1019
- .digest('hex')
1020
- .slice(0, 12);
1021
- /**
1022
- * Remove older compiled cache files for a given source base name, keeping
1023
- * at most `keep` most-recent files. Errors are ignored by design.
1024
- */
1025
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
1026
- try {
1027
- const entries = await fs.readdir(cacheDir);
1028
- const mine = entries
1029
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
1030
- .map((f) => path.join(cacheDir, f));
1031
- if (mine.length <= keep)
1032
- return;
1033
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
1034
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
1035
- const toDelete = stats.slice(keep).map((s) => s.p);
1036
- await Promise.all(toDelete.map(async (p) => {
1037
- try {
1038
- await fs.remove(p);
1039
- }
1040
- catch {
1041
- // best-effort cleanup
1042
- }
1043
- }));
1044
- }
1045
- catch {
1046
- // best-effort cleanup
1047
- }
1048
- };
1049
- /**
1050
- * Load a module default export from a JS/TS file with robust fallbacks:
1051
- * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1052
- * 1) try direct import (if a TS loader is active),
1053
- * 2) esbuild bundle to a temp ESM file,
1054
- * 3) typescript.transpileModule fallback for simple modules.
1055
- *
1056
- * @param absPath - absolute path to source file
1057
- * @param cacheDirName - cache subfolder under .tsbuild
1058
- */
1059
- const loadModuleDefault = async (absPath, cacheDirName) => {
1060
- const ext = path.extname(absPath).toLowerCase();
1061
- const fileUrl = url.pathToFileURL(absPath).toString();
1062
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1063
- return importDefault(fileUrl);
1064
- }
1065
- // Try direct import first (TS loader active)
1066
- try {
1067
- const dyn = await importDefault(fileUrl);
1068
- if (dyn)
1069
- return dyn;
1070
- }
1071
- catch {
1072
- /* fall through */
1073
- }
1074
- const stat = await fs.stat(absPath);
1075
- const hash = cacheHash(absPath, stat.mtimeMs);
1076
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
1077
- await fs.ensureDir(cacheDir);
1078
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
1079
- // Try esbuild
1080
- try {
1081
- const esbuild = (await import('esbuild'));
1082
- await esbuild.build({
1083
- entryPoints: [absPath],
1084
- bundle: true,
1085
- platform: 'node',
1086
- format: 'esm',
1087
- target: 'node20',
1088
- outfile: cacheFile,
1089
- sourcemap: false,
1090
- logLevel: 'silent',
1091
- });
1092
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1093
- // Best-effort: trim older cache files for this source.
1094
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1095
- return result;
1096
- }
1097
- catch {
1098
- /* fall through to TS transpile */
1099
- }
1100
- // TypeScript transpile fallback
1101
- try {
1102
- const ts = (await import('typescript'));
1103
- const code = await fs.readFile(absPath, 'utf-8');
1104
- const out = ts.transpileModule(code, {
1105
- compilerOptions: {
1106
- module: 'ESNext',
1107
- target: 'ES2022',
1108
- moduleResolution: 'NodeNext',
1109
- },
1110
- }).outputText;
1111
- await fs.writeFile(cacheFile, out, 'utf-8');
1112
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1113
- // Best-effort: trim older cache files for this source.
1114
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1115
- return result;
1116
- }
1117
- catch {
1118
- // Caller decides final error wording; rethrow for upstream mapping.
1119
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
1120
- }
1121
- };
1122
-
1123
- /**
1124
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
1125
- *
1126
- * @param options - `GetDotenvOptions` object
1127
- * @returns The combined parsed dotenv object.
1128
- * * @example Load from the project root with default tokens
1129
- * ```ts
1130
- * const vars = await getDotenv();
1131
- * console.log(vars.MY_SETTING);
1132
- * ```
1133
- *
1134
- * @example Load from multiple paths and a specific environment
1135
- * ```ts
1136
- * const vars = await getDotenv({
1137
- * env: 'dev',
1138
- * dotenvToken: '.testenv',
1139
- * privateToken: 'secret',
1140
- * paths: ['./', './packages/app'],
1141
- * });
1142
- * ```
1143
- *
1144
- * @example Use dynamic variables
1145
- * ```ts
1146
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
1147
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
1148
- * ```
1149
- *
1150
- * @remarks
1151
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
1152
- * into `process.env` as a side effect.
1153
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
1154
- * The path is resolved after expansion, so it may reference previously loaded vars.
1155
- *
1156
- * @throws Error when a dynamic module is present but cannot be imported.
1157
- * @throws Error when an output path was requested but could not be resolved.
1158
- */
1159
- const getDotenv = async (options = {}) => {
1160
- // Apply defaults.
1161
- 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);
1162
- // Read .env files.
1163
- const loaded = paths.length
1164
- ? await paths.reduce(async (e, p) => {
1165
- const publicGlobal = excludePublic || excludeGlobal
1166
- ? Promise.resolve({})
1167
- : readDotenv(path.resolve(p, dotenvToken));
1168
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1169
- ? Promise.resolve({})
1170
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1171
- const privateGlobal = excludePrivate || excludeGlobal
1172
- ? Promise.resolve({})
1173
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1174
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1175
- ? Promise.resolve({})
1176
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1177
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1178
- e,
1179
- publicGlobal,
1180
- publicEnv,
1181
- privateGlobal,
1182
- privateEnv,
1183
- ]);
1184
- return {
1185
- ...eResolved,
1186
- ...publicGlobalResolved,
1187
- ...publicEnvResolved,
1188
- ...privateGlobalResolved,
1189
- ...privateEnvResolved,
1190
- };
1191
- }, Promise.resolve({}))
1192
- : {};
1193
- const outputKey = nanoid.nanoid();
1194
- const dotenv = dotenvExpandAll({
1195
- ...loaded,
1196
- ...vars,
1197
- ...(outputPath ? { [outputKey]: outputPath } : {}),
1198
- }, { progressive: true });
1199
- // Process dynamic variables. Programmatic option takes precedence over path.
1200
- if (!excludeDynamic) {
1201
- let dynamic = undefined;
1202
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1203
- dynamic = options.dynamic;
1204
- }
1205
- else if (dynamicPath) {
1206
- const absDynamicPath = path.resolve(dynamicPath);
1207
- if (await fs.exists(absDynamicPath)) {
1208
- try {
1209
- dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1210
- }
1211
- catch {
1212
- // Preserve legacy error text for compatibility with tests/docs.
1213
- throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1214
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1215
- }
1216
- }
1217
- }
1218
- if (dynamic) {
1219
- try {
1220
- for (const key in dynamic)
1221
- Object.assign(dotenv, {
1222
- [key]: typeof dynamic[key] === 'function'
1223
- ? dynamic[key](dotenv, env ?? defaultEnv)
1224
- : dynamic[key],
1225
- });
1226
- }
1227
- catch {
1228
- throw new Error(`Unable to evaluate dynamic variables.`);
1229
- }
1230
- }
1231
- }
1232
- // Write output file.
1233
- let resultDotenv = dotenv;
1234
- if (outputPath) {
1235
- const outputPathResolved = dotenv[outputKey];
1236
- if (!outputPathResolved)
1237
- throw new Error('Output path not found.');
1238
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1239
- await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
1240
- const value = dotenvForOutput[key] ?? '';
1241
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1242
- }, ''), { encoding: 'utf-8' });
1243
- resultDotenv = dotenvForOutput;
1244
- }
1245
- // Log result.
1246
- if (log) {
1247
- const redactFlag = options.redact ?? false;
1248
- const redactPatterns = options.redactPatterns ?? undefined;
1249
- const redOpts = {};
1250
- if (redactFlag)
1251
- redOpts.redact = true;
1252
- if (redactFlag && Array.isArray(redactPatterns))
1253
- redOpts.redactPatterns = redactPatterns;
1254
- const bag = redactFlag
1255
- ? redactObject(resultDotenv, redOpts)
1256
- : { ...resultDotenv };
1257
- logger.log(bag);
1258
- // Entropy warnings: once-per-key-per-run (presentation only)
1259
- const warnEntropyVal = options.warnEntropy ?? true;
1260
- const entropyThresholdVal = options
1261
- .entropyThreshold;
1262
- const entropyMinLengthVal = options
1263
- .entropyMinLength;
1264
- const entropyWhitelistVal = options
1265
- .entropyWhitelist;
1266
- const entOpts = {};
1267
- if (typeof warnEntropyVal === 'boolean')
1268
- entOpts.warnEntropy = warnEntropyVal;
1269
- if (typeof entropyThresholdVal === 'number')
1270
- entOpts.entropyThreshold = entropyThresholdVal;
1271
- if (typeof entropyMinLengthVal === 'number')
1272
- entOpts.entropyMinLength = entropyMinLengthVal;
1273
- if (Array.isArray(entropyWhitelistVal))
1274
- entOpts.entropyWhitelist = entropyWhitelistVal;
1275
- for (const [k, v] of Object.entries(resultDotenv)) {
1276
- maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1277
- logger.log(line);
1278
- });
1279
- }
1280
- }
1281
- // Load process.env.
1282
- if (loadProcess)
1283
- Object.assign(process.env, resultDotenv);
1284
- return resultDotenv;
1285
- };
1286
-
1287
- /**
1288
- * Deep interpolation utility for string leaves.
1289
- * - Expands string values using dotenv-style expansion against the provided envRef.
1290
- * - Preserves non-strings as-is.
1291
- * - Does not recurse into arrays (arrays are returned unchanged).
1292
- *
1293
- * Intended for:
1294
- * - Phase C option/config interpolation after composing ctx.dotenv.
1295
- * - Per-plugin config slice interpolation before afterResolve.
1296
- */
1297
- /** @internal */
1298
- const isPlainObject = (v) => v !== null &&
1299
- typeof v === 'object' &&
1300
- !Array.isArray(v) &&
1301
- Object.getPrototypeOf(v) === Object.prototype;
1302
- /**
1303
- * Deeply interpolate string leaves against envRef.
1304
- * Arrays are not recursed into; they are returned unchanged.
1305
- *
1306
- * @typeParam T - Shape of the input value.
1307
- * @param value - Input value (object/array/primitive).
1308
- * @param envRef - Reference environment for interpolation.
1309
- * @returns A new value with string leaves interpolated.
1310
- */
1311
- const interpolateDeep = (value, envRef) => {
1312
- // Strings: expand and return
1313
- if (typeof value === 'string') {
1314
- const out = dotenvExpand(value, envRef);
1315
- // dotenvExpand returns string | undefined; preserve original on undefined
1316
- return (out ?? value);
1317
- }
1318
- // Arrays: return as-is (no recursion)
1319
- if (Array.isArray(value)) {
1320
- return value;
1321
- }
1322
- // Plain objects: shallow clone and recurse into values
1323
- if (isPlainObject(value)) {
1324
- const src = value;
1325
- const out = {};
1326
- for (const [k, v] of Object.entries(src)) {
1327
- // Recurse for strings/objects; keep arrays as-is; preserve other scalars
1328
- if (typeof v === 'string')
1329
- out[k] = dotenvExpand(v, envRef) ?? v;
1330
- else if (Array.isArray(v))
1331
- out[k] = v;
1332
- else if (isPlainObject(v))
1333
- out[k] = interpolateDeep(v, envRef);
1334
- else
1335
- out[k] = v;
1336
- }
1337
- return out;
1338
- }
1339
- // Other primitives/types: return as-is
1340
- return value;
1341
- };
1342
-
1343
- /**
1344
- * Compute the dotenv context for the host (uses the config loader/overlay path).
1345
- * - Resolves and validates options strictly (host-only).
1346
- * - Applies file cascade, overlays, dynamics, and optional effects.
1347
- * - Merges and validates per-plugin config slices (when provided).
1348
- *
1349
- * @param customOptions - Partial options from the current invocation.
1350
- * @param plugins - Installed plugins (for config validation).
1351
- * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
1352
- const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1353
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1354
- const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1355
- // Always-on loader path
1356
- // 1) Base from files only (no dynamic, no programmatic vars)
1357
- const base = await getDotenv({
1358
- ...validated,
1359
- // Build a pure base without side effects or logging.
1360
- excludeDynamic: true,
1361
- vars: {},
1362
- log: false,
1363
- loadProcess: false,
1364
- outputPath: undefined,
1365
- });
1366
- // 2) Discover config sources and overlay
1367
- const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1368
- const dotenvOverlaid = overlayEnv({
1369
- base,
1370
- env: validated.env ?? validated.defaultEnv,
1371
- configs: sources,
1372
- ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1373
- });
1374
- // Helper to apply a dynamic map progressively.
1375
- const applyDynamic = (target, dynamic, env) => {
1376
- if (!dynamic)
1377
- return;
1378
- for (const key of Object.keys(dynamic)) {
1379
- const value = typeof dynamic[key] === 'function'
1380
- ? dynamic[key](target, env)
1381
- : dynamic[key];
1382
- Object.assign(target, { [key]: value });
1383
- }
1384
- };
1385
- // 3) Apply dynamics in order
1386
- const dotenv = { ...dotenvOverlaid };
1387
- applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1388
- applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1389
- applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1390
- applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1391
- // file dynamicPath (lowest)
1392
- if (validated.dynamicPath) {
1393
- const absDynamicPath = path.resolve(validated.dynamicPath);
1394
- try {
1395
- const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
1396
- applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
1397
- }
1398
- catch {
1399
- throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
1400
- }
1401
- }
1402
- // 4) Output/log/process merge
1403
- if (validated.outputPath) {
1404
- await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
1405
- const value = dotenv[key] ?? '';
1406
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1407
- }, ''), { encoding: 'utf-8' });
1408
- }
1409
- const logger = validated.logger ?? console;
1410
- if (validated.log)
1411
- logger.log(dotenv);
1412
- if (validated.loadProcess)
1413
- Object.assign(process.env, dotenv);
1414
- // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
1415
- const packagedPlugins = (sources.packaged &&
1416
- sources.packaged.plugins) ??
1417
- {};
1418
- const publicPlugins = (sources.project?.public &&
1419
- sources.project.public.plugins) ??
1420
- {};
1421
- const localPlugins = (sources.project?.local &&
1422
- sources.project.local.plugins) ??
1423
- {};
1424
- const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
1425
- for (const p of plugins) {
1426
- if (!p.id)
1427
- continue;
1428
- const slice = mergedPluginConfigs[p.id];
1429
- if (slice === undefined)
1430
- continue;
1431
- // Per-plugin interpolation just before validation/afterResolve:
1432
- // precedence: process.env wins over ctx.dotenv for slice defaults.
1433
- const envRef = {
1434
- ...dotenv,
1435
- ...process.env,
1436
- };
1437
- const interpolated = interpolateDeep(slice, envRef);
1438
- // Validate if a schema is provided; otherwise accept interpolated slice as-is.
1439
- if (p.configSchema) {
1440
- const parsed = p.configSchema.safeParse(interpolated);
1441
- if (!parsed.success) {
1442
- const msgs = parsed.error.issues
1443
- .map((i) => `${i.path.join('.')}: ${i.message}`)
1444
- .join('\n');
1445
- throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
1446
- }
1447
- mergedPluginConfigs[p.id] = parsed.data;
1448
- }
1449
- else {
1450
- mergedPluginConfigs[p.id] = interpolated;
1451
- }
1452
- }
1453
- return {
1454
- optionsResolved: validated,
1455
- dotenv: dotenv,
1456
- plugins: {},
1457
- pluginConfigs: mergedPluginConfigs,
1458
- };
1459
- };
1460
-
1461
- const HOST_META_URL = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cliHost.cjs', document.baseURI).href));
1462
- const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
1463
- const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
1464
- const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1465
- /**
1466
- * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
1467
- *
1468
- * Responsibilities:
1469
- * - Resolve options strictly and compute dotenv context (resolveAndLoad).
1470
- * - Expose a stable accessor for the current context (getCtx).
1471
- * - Provide a namespacing helper (ns).
1472
- * - Support composable plugins with parent → children install and afterResolve.
1473
- *
1474
- * NOTE: This host is additive and does not alter the legacy CLI.
1475
- */
1476
- let GetDotenvCli$1 = class GetDotenvCli extends commander.Command {
1477
- /** Registered top-level plugins (composition happens via .use()) */
1478
- _plugins = [];
1479
- /** One-time installation guard */
1480
- _installed = false;
1481
- /** Optional header line to prepend in help output */
1482
- [HELP_HEADER_SYMBOL];
1483
- constructor(alias = 'getdotenv') {
1484
- super(alias);
1485
- // Ensure subcommands that use passThroughOptions can be attached safely.
1486
- // Commander requires parent commands to enable positional options when a
1487
- // child uses passThroughOptions.
1488
- this.enablePositionalOptions();
1489
- // Configure grouped help: show only base options in default "Options";
1490
- // append App/Plugin sections after default help.
1491
- this.configureHelp({
1492
- visibleOptions: (cmd) => {
1493
- const all = cmd.options ??
1494
- [];
1495
- const base = all.filter((opt) => {
1496
- const group = opt.__group;
1497
- return group === 'base';
1498
- });
1499
- // Sort: short-aliased options first, then long-only; stable by flags.
1500
- const hasShort = (opt) => {
1501
- const flags = opt.flags ?? '';
1502
- // Matches "-x," or starting "-x " before any long
1503
- return /(^|\s|,)-[A-Za-z]/.test(flags);
1504
- };
1505
- const byFlags = (opt) => opt.flags ?? '';
1506
- base.sort((a, b) => {
1507
- const aS = hasShort(a) ? 1 : 0;
1508
- const bS = hasShort(b) ? 1 : 0;
1509
- return bS - aS || byFlags(a).localeCompare(byFlags(b));
1510
- });
1511
- return base;
1512
- },
1513
- });
1514
- this.addHelpText('beforeAll', () => {
1515
- const header = this[HELP_HEADER_SYMBOL];
1516
- return header && header.length > 0 ? `${header}\n\n` : '';
1517
- });
1518
- this.addHelpText('afterAll', (ctx) => this.#renderOptionGroups(ctx.command));
1519
- // Skeleton preSubcommand hook: produce a context if absent, without
1520
- // mutating process.env. The passOptions hook (when installed) will // compute the final context using merged CLI options; keeping
1521
- // loadProcess=false here avoids leaking dotenv values into the parent
1522
- // process env before subcommands execute.
1523
- this.hook('preSubcommand', async () => {
1524
- if (this.getCtx())
1525
- return;
1526
- await this.resolveAndLoad({ loadProcess: false });
1527
- });
1528
- }
1529
- /**
1530
- * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
1531
- */
1532
- async resolveAndLoad(customOptions = {}) {
1533
- // Resolve defaults, then validate strictly under the new host.
1534
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1535
- getDotenvOptionsSchemaResolved.parse(optionsResolved);
1536
- // Delegate the heavy lifting to the shared helper (guarded path supported).
1537
- const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
1538
- // Persist context on the instance for later access.
1539
- this[CTX_SYMBOL] =
1540
- ctx;
1541
- // Ensure plugins are installed exactly once, then run afterResolve.
1542
- await this.install();
1543
- await this._runAfterResolve(ctx);
1544
- return ctx;
1545
- }
1546
- /**
1547
- * Retrieve the current invocation context (if any).
1548
- */
1549
- getCtx() {
1550
- return this[CTX_SYMBOL];
1551
- }
1552
- /**
1553
- * Retrieve the merged root CLI options bag (if set by passOptions()).
1554
- * Downstream-safe: no generics required.
1555
- */
1556
- getOptions() {
1557
- return this[OPTS_SYMBOL];
1558
- }
1559
- /** Internal: set the merged root options bag for this run. */
1560
- _setOptionsBag(bag) {
1561
- this[OPTS_SYMBOL] = bag;
1562
- }
1563
- /** * Convenience helper to create a namespaced subcommand.
1564
- */
1565
- ns(name) {
1566
- return this.command(name);
1567
- }
1568
- /**
1569
- * Tag options added during the provided callback as 'app' for grouped help.
1570
- * Allows downstream apps to demarcate their root-level options.
1571
- */
1572
- tagAppOptions(fn) {
1573
- const root = this;
1574
- const originalAddOption = root.addOption.bind(root);
1575
- const originalOption = root.option.bind(root);
1576
- const tagLatest = (cmd, group) => {
1577
- const optsArr = cmd.options;
1578
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1579
- const last = optsArr[optsArr.length - 1];
1580
- last.__group = group;
1581
- }
1582
- };
1583
- root.addOption = function patchedAdd(opt) {
1584
- opt.__group = 'app';
1585
- return originalAddOption(opt);
1586
- };
1587
- root.option = function patchedOption(...args) {
1588
- const ret = originalOption(...args);
1589
- tagLatest(this, 'app');
1590
- return ret;
1591
- };
1592
- try {
1593
- return fn(root);
1594
- }
1595
- finally {
1596
- root.addOption = originalAddOption;
1597
- root.option = originalOption;
1598
- }
1599
- }
1600
- /**
1601
- * Branding helper: set CLI name/description/version and optional help header.
1602
- * If version is omitted and importMetaUrl is provided, attempts to read the
1603
- * nearest package.json version (best-effort; non-fatal on failure).
1604
- */
1605
- async brand(args) {
1606
- const { name, description, version, importMetaUrl, helpHeader } = args;
1607
- if (typeof name === 'string' && name.length > 0)
1608
- this.name(name);
1609
- if (typeof description === 'string')
1610
- this.description(description);
1611
- let v = version;
1612
- if (!v && importMetaUrl) {
1613
- try {
1614
- const fromUrl = url.fileURLToPath(importMetaUrl);
1615
- const pkgDir = await packageDirectory.packageDirectory({ cwd: fromUrl });
1616
- if (pkgDir) {
1617
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1618
- const pkg = JSON.parse(txt);
1619
- if (pkg.version)
1620
- v = pkg.version;
1621
- }
1622
- }
1623
- catch {
1624
- // best-effort only
1625
- }
1626
- }
1627
- if (v)
1628
- this.version(v);
1629
- // Help header:
1630
- // - If caller provides helpHeader, use it.
1631
- // - Otherwise, when a version is known, default to "<name> v<version>".
1632
- if (typeof helpHeader === 'string') {
1633
- this[HELP_HEADER_SYMBOL] = helpHeader;
1634
- }
1635
- else if (v) {
1636
- // Use the current command name (possibly overridden by 'name' above).
1637
- const header = `${this.name()} v${v}`;
1638
- this[HELP_HEADER_SYMBOL] = header;
1639
- }
1640
- return this;
1641
- }
1642
- /**
1643
- * Register a plugin for installation (parent level).
1644
- * Installation occurs on first resolveAndLoad() (or explicit install()).
1645
- */
1646
- use(plugin) {
1647
- this._plugins.push(plugin);
1648
- // Immediately run setup so subcommands exist before parsing.
1649
- const setupOne = (p) => {
1650
- p.setup(this);
1651
- for (const child of p.children)
1652
- setupOne(child);
1653
- };
1654
- setupOne(plugin);
1655
- return this;
1656
- }
1657
- /**
1658
- * Install all registered plugins in parent → children (pre-order).
1659
- * Runs only once per CLI instance.
1660
- */
1661
- async install() {
1662
- // Setup is performed immediately in use(); here we only guard for afterResolve.
1663
- this._installed = true;
1664
- // Satisfy require-await without altering behavior.
1665
- await Promise.resolve();
1666
- }
1667
- /**
1668
- * Run afterResolve hooks for all plugins (parent → children).
1669
- */
1670
- async _runAfterResolve(ctx) {
1671
- const run = async (p) => {
1672
- if (p.afterResolve)
1673
- await p.afterResolve(this, ctx);
1674
- for (const child of p.children)
1675
- await run(child);
1676
- };
1677
- for (const p of this._plugins)
1678
- await run(p);
1679
- }
1680
- // Render App/Plugin grouped options appended after default help.
1681
- #renderOptionGroups(cmd) {
1682
- const all = cmd.options ?? [];
1683
- const byGroup = new Map();
1684
- for (const o of all) {
1685
- const opt = o;
1686
- const g = opt.__group;
1687
- if (!g || g === 'base')
1688
- continue; // base handled by default help
1689
- const rows = byGroup.get(g) ?? [];
1690
- rows.push({
1691
- flags: opt.flags ?? '',
1692
- description: opt.description ?? '',
1693
- });
1694
- byGroup.set(g, rows);
1695
- }
1696
- if (byGroup.size === 0)
1697
- return '';
1698
- const renderRows = (title, rows) => {
1699
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1700
- // Sort within group: short-aliased flags first
1701
- rows.sort((a, b) => {
1702
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1703
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1704
- return bS - aS || a.flags.localeCompare(b.flags);
1705
- });
1706
- const lines = rows
1707
- .map((r) => {
1708
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1709
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1710
- })
1711
- .join('\n');
1712
- return `\n${title}:\n${lines}\n`;
1713
- };
1714
- let out = '';
1715
- // App options (if any)
1716
- const app = byGroup.get('app');
1717
- if (app && app.length > 0) {
1718
- out += renderRows('App options', app);
1719
- }
1720
- // Plugin groups sorted by id
1721
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1722
- pluginKeys.sort((a, b) => a.localeCompare(b));
1723
- for (const k of pluginKeys) {
1724
- const id = k.slice('plugin:'.length) || '(unknown)';
1725
- const rows = byGroup.get(k) ?? [];
1726
- if (rows.length > 0) {
1727
- out += renderRows(`Plugin options — ${id}`, rows);
1728
- }
1729
- }
1730
- return out;
1731
- }
1732
- };
1733
-
1734
- /** src/cliHost/definePlugin.ts
1735
- * Plugin contracts for the GetDotenv CLI host.
1736
- *
1737
- * This module exposes a structural public interface for the host that plugins
1738
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
1739
- * nominal class identity issues (private fields) in downstream consumers.
1740
- */
1741
- /**
1742
- * Define a GetDotenv CLI plugin with compositional helpers.
1743
- *
1744
- * @example
1745
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
1746
- * .use(childA)
1747
- * .use(childB);
1748
- */
1749
- const definePlugin = (spec) => {
1750
- const { children = [], ...rest } = spec;
1751
- const plugin = {
1752
- ...rest,
1753
- children: [...children],
1754
- use(child) {
1755
- this.children.push(child);
1756
- return this;
1757
- },
1758
- };
1759
- return plugin;
1760
- };
1761
-
1762
- /**
1763
- * GetDotenvCli with root helpers as real class methods.
1764
- * - attachRootOptions: installs legacy/base root flags on the command.
1765
- * - passOptions: merges flags (parent \< current), computes dotenv context once,
1766
- * runs validation, and persists merged options for nested flows.
1767
- */
1768
- class GetDotenvCli extends GetDotenvCli$1 {
1769
- /**
1770
- * Attach legacy root flags to this CLI instance. Defaults come from
1771
- * baseRootOptionDefaults when none are provided.
1772
- */
1773
- attachRootOptions(defaults, opts) {
1774
- const d = (defaults ?? baseRootOptionDefaults);
1775
- attachRootOptions(this, d, opts);
1776
- return this;
1777
- }
1778
- /**
1779
- * Install preSubcommand/preAction hooks that:
1780
- * - Merge options (parent round-trip + current invocation) using resolveCliOptions.
1781
- * - Persist the merged bag on the current command and on the host (for ergonomics).
1782
- * - Compute the dotenv context once via resolveAndLoad(serviceOptions).
1783
- * - Validate the composed env against discovered config (warn or --strict fail).
1784
- */
1785
- passOptions(defaults) {
1786
- const d = (defaults ?? baseRootOptionDefaults);
1787
- this.hook('preSubcommand', async (thisCommand) => {
1788
- const raw = thisCommand.opts();
1789
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1790
- // Persist merged options (for nested behavior and ergonomic access).
1791
- thisCommand.getDotenvCliOptions =
1792
- merged;
1793
- this._setOptionsBag(merged);
1794
- // Build service options and compute context (always-on loader path).
1795
- const serviceOptions = getDotenvCliOptions2Options(merged);
1796
- await this.resolveAndLoad(serviceOptions);
1797
- // Global validation: once after Phase C using config sources.
1798
- try {
1799
- const ctx = this.getCtx();
1800
- const dotenv = (ctx?.dotenv ?? {});
1801
- const sources = await resolveGetDotenvConfigSources((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cliHost.cjs', document.baseURI).href)));
1802
- const issues = validateEnvAgainstSources(dotenv, sources);
1803
- if (Array.isArray(issues) && issues.length > 0) {
1804
- const logger = (merged
1805
- .logger ?? console);
1806
- const emit = logger.error ?? logger.log;
1807
- issues.forEach((m) => {
1808
- emit(m);
1809
- });
1810
- if (merged.strict) {
1811
- process.exit(1);
1812
- }
1813
- }
1814
- }
1815
- catch {
1816
- // Be tolerant: do not crash non-strict flows on unexpected validator failures.
1817
- }
1818
- });
1819
- // Also handle root-level flows (no subcommand) so option-aliases can run
1820
- // with the same merged options and context without duplicating logic.
1821
- this.hook('preAction', async (thisCommand) => {
1822
- const raw = thisCommand.opts();
1823
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1824
- thisCommand.getDotenvCliOptions =
1825
- merged;
1826
- this._setOptionsBag(merged);
1827
- // Avoid duplicate heavy work if a context is already present.
1828
- if (!this.getCtx()) {
1829
- const serviceOptions = getDotenvCliOptions2Options(merged);
1830
- await this.resolveAndLoad(serviceOptions);
1831
- try {
1832
- const ctx = this.getCtx();
1833
- const dotenv = (ctx?.dotenv ?? {});
1834
- const sources = await resolveGetDotenvConfigSources((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cliHost.cjs', document.baseURI).href)));
1835
- const issues = validateEnvAgainstSources(dotenv, sources);
1836
- if (Array.isArray(issues) && issues.length > 0) {
1837
- const logger = (merged
1838
- .logger ?? console);
1839
- const emit = logger.error ?? logger.log;
1840
- issues.forEach((m) => {
1841
- emit(m);
1842
- });
1843
- if (merged.strict) {
1844
- process.exit(1);
1845
- }
1846
- }
1847
- }
1848
- catch {
1849
- // Tolerate validation side-effects in non-strict mode.
1850
- }
1851
- }
1852
- });
1853
- return this;
1854
- }
1855
- }
1856
- /**
1857
- * Helper to retrieve the merged root options bag from any action handler
1858
- * that only has access to thisCommand. Avoids structural casts.
1859
- */
1860
- const readMergedOptions = (cmd) => {
1861
- // Ascend to the root command
1862
- let root = cmd;
1863
- while (root.parent) {
1864
- root = root.parent;
1865
- }
1866
- const hostAny = root;
1867
- return typeof hostAny.getOptions === 'function'
1868
- ? hostAny.getOptions()
1869
- : root
1870
- .getDotenvCliOptions;
1871
- };
1872
-
1873
- exports.GetDotenvCli = GetDotenvCli;
1874
- exports.definePlugin = definePlugin;
1875
- exports.readMergedOptions = readMergedOptions;