@karmaniverous/get-dotenv 6.2.3 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +1 -0
  2. package/dist/chunks/AwsRestJsonProtocol-Dv5q8CFK.mjs +932 -0
  3. package/dist/chunks/createCli-BSn6Be40.mjs +440 -0
  4. package/dist/chunks/externalDataInterceptor-pqHO-Qmn.mjs +19 -0
  5. package/dist/chunks/getSSOTokenFromFile-otmZHSRV.mjs +22 -0
  6. package/dist/chunks/helpConfig-CGejgwWW.mjs +12 -0
  7. package/dist/chunks/index-B18W-ELX.mjs +273 -0
  8. package/dist/chunks/index-BNcKuiBy.mjs +9375 -0
  9. package/dist/chunks/index-Bi0RIILn.mjs +25 -0
  10. package/dist/chunks/index-BqZ3PB6c.mjs +375 -0
  11. package/dist/chunks/index-C4Ac6feq.mjs +355 -0
  12. package/dist/chunks/index-C6uLiKpC.mjs +703 -0
  13. package/dist/chunks/index-CGg5wWCm.mjs +188 -0
  14. package/dist/chunks/index-CXpZ0pei.mjs +579 -0
  15. package/dist/chunks/index-CYoFYXZv.mjs +103 -0
  16. package/dist/chunks/index-DFNcs3pR.mjs +444 -0
  17. package/dist/chunks/index-DLQEHTw4.mjs +83 -0
  18. package/dist/chunks/index-DtRaL61T.mjs +380 -0
  19. package/dist/chunks/index-eZMlmESW.mjs +522 -0
  20. package/dist/chunks/invoke-DuRPU1oC.mjs +60 -0
  21. package/dist/chunks/loadModuleDefault-Dj8B3Stt.mjs +123 -0
  22. package/dist/chunks/loadSso-CJ_XUhEj.mjs +413 -0
  23. package/dist/chunks/loader-CePOf74i.mjs +347 -0
  24. package/dist/chunks/overlayEnv-Bqh_kPGA.mjs +235 -0
  25. package/dist/chunks/package-boo9EyYs.mjs +5 -0
  26. package/dist/chunks/parseKnownFiles-B6x1cUmR.mjs +23 -0
  27. package/dist/chunks/readMergedOptions-DLBDzpXX.mjs +1627 -0
  28. package/dist/chunks/resolveCliOptions-_qtsVxda.mjs +139 -0
  29. package/dist/chunks/sdk-stream-mixin-DCdC70Up.mjs +167 -0
  30. package/dist/chunks/spawnEnv-CQwFu7ZJ.mjs +307 -0
  31. package/dist/chunks/types-DdqcXCV1.mjs +59 -0
  32. package/dist/chunks/validate-CDl0rE6k.mjs +61 -0
  33. package/dist/cli.mjs +39 -19307
  34. package/dist/cliHost.mjs +21 -2800
  35. package/dist/config.mjs +11 -509
  36. package/dist/env-overlay.mjs +7 -337
  37. package/dist/getdotenv.cli.mjs +39 -19305
  38. package/dist/index.d.ts +485 -2
  39. package/dist/index.mjs +657 -19322
  40. package/dist/plugins-aws.d.ts +1 -4
  41. package/dist/plugins-aws.mjs +66 -2568
  42. package/dist/plugins-batch.mjs +17 -2573
  43. package/dist/plugins-cmd.mjs +20 -3094
  44. package/dist/plugins-init.d.ts +8 -0
  45. package/dist/plugins-init.mjs +85 -2297
  46. package/dist/plugins.mjs +36 -18817
  47. package/package.json +1 -2
  48. package/dist/templates/cli/index.ts +0 -25
  49. package/dist/templates/cli/plugins/hello/defaultAction.ts +0 -27
  50. package/dist/templates/cli/plugins/hello/index.ts +0 -26
  51. package/dist/templates/cli/plugins/hello/options.ts +0 -31
  52. package/dist/templates/cli/plugins/hello/strangerAction.ts +0 -20
  53. package/dist/templates/cli/plugins/hello/types.ts +0 -13
  54. package/dist/templates/config/js/getdotenv.config.js +0 -20
  55. package/dist/templates/config/json/local/getdotenv.config.local.json +0 -7
  56. package/dist/templates/config/json/public/getdotenv.config.json +0 -9
  57. package/dist/templates/config/public/getdotenv.config.json +0 -8
  58. package/dist/templates/config/ts/getdotenv.config.ts +0 -28
  59. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +0 -7
  60. package/dist/templates/config/yaml/public/getdotenv.config.yaml +0 -7
  61. package/dist/templates/defaultAction.ts +0 -27
  62. package/dist/templates/getdotenv.config.js +0 -20
  63. package/dist/templates/getdotenv.config.json +0 -9
  64. package/dist/templates/getdotenv.config.local.json +0 -7
  65. package/dist/templates/getdotenv.config.local.yaml +0 -7
  66. package/dist/templates/getdotenv.config.ts +0 -28
  67. package/dist/templates/getdotenv.config.yaml +0 -7
  68. package/dist/templates/hello/defaultAction.ts +0 -27
  69. package/dist/templates/hello/index.ts +0 -26
  70. package/dist/templates/hello/options.ts +0 -31
  71. package/dist/templates/hello/strangerAction.ts +0 -20
  72. package/dist/templates/hello/types.ts +0 -13
  73. package/dist/templates/index.ts +0 -26
  74. package/dist/templates/js/getdotenv.config.js +0 -20
  75. package/dist/templates/json/local/getdotenv.config.local.json +0 -7
  76. package/dist/templates/json/public/getdotenv.config.json +0 -9
  77. package/dist/templates/local/getdotenv.config.local.json +0 -7
  78. package/dist/templates/local/getdotenv.config.local.yaml +0 -7
  79. package/dist/templates/options.ts +0 -31
  80. package/dist/templates/plugins/hello/defaultAction.ts +0 -27
  81. package/dist/templates/plugins/hello/index.ts +0 -26
  82. package/dist/templates/plugins/hello/options.ts +0 -31
  83. package/dist/templates/plugins/hello/strangerAction.ts +0 -20
  84. package/dist/templates/plugins/hello/types.ts +0 -13
  85. package/dist/templates/public/getdotenv.config.json +0 -9
  86. package/dist/templates/public/getdotenv.config.yaml +0 -7
  87. package/dist/templates/strangerAction.ts +0 -20
  88. package/dist/templates/ts/getdotenv.config.ts +0 -28
  89. package/dist/templates/types.ts +0 -13
  90. package/dist/templates/yaml/local/getdotenv.config.local.yaml +0 -7
  91. package/dist/templates/yaml/public/getdotenv.config.yaml +0 -7
@@ -1,337 +1,7 @@
1
- import fs from 'fs-extra';
2
- import { createHash } from 'crypto';
3
- import path from 'path';
4
- import url from 'url';
5
-
6
- /**
7
- * Dotenv expansion utilities.
8
- *
9
- * This module implements recursive expansion of environment-variable
10
- * references in strings and records. It supports both whitespace and
11
- * bracket syntaxes with optional defaults:
12
- *
13
- * - Whitespace: `$VAR[:default]`
14
- * - Bracketed: `${VAR[:default]}`
15
- *
16
- * Escaped dollar signs (`\$`) are preserved.
17
- * Unknown variables resolve to empty string unless a default is provided.
18
- */
19
- /**
20
- * Like String.prototype.search but returns the last index.
21
- * @internal
22
- */
23
- const searchLast = (str, rgx) => {
24
- const matches = Array.from(str.matchAll(rgx));
25
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
26
- };
27
- const replaceMatch = (value, match, ref) => {
28
- /**
29
- * @internal
30
- */
31
- const group = match[0];
32
- const key = match[1];
33
- const defaultValue = match[2];
34
- if (!key)
35
- return value;
36
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
37
- return interpolate(replacement, ref);
38
- };
39
- const interpolate = (value = '', ref = {}) => {
40
- /**
41
- * @internal
42
- */
43
- // if value is falsy, return it as is
44
- if (!value)
45
- return value;
46
- // get position of last unescaped dollar sign
47
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
48
- // return value if none found
49
- if (lastUnescapedDollarSignIndex === -1)
50
- return value;
51
- // evaluate the value tail
52
- const tail = value.slice(lastUnescapedDollarSignIndex);
53
- // find whitespace pattern: $KEY:DEFAULT
54
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
55
- const whitespaceMatch = whitespacePattern.exec(tail);
56
- if (whitespaceMatch != null)
57
- return replaceMatch(value, whitespaceMatch, ref);
58
- else {
59
- // find bracket pattern: ${KEY:DEFAULT}
60
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
61
- const bracketMatch = bracketPattern.exec(tail);
62
- if (bracketMatch != null)
63
- return replaceMatch(value, bracketMatch, ref);
64
- }
65
- return value;
66
- };
67
- /**
68
- * Recursively expands environment variables in a string. Variables may be
69
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
70
- * Unknown variables will expand to an empty string.
71
- *
72
- * @param value - The string to expand.
73
- * @param ref - The reference object to use for variable expansion.
74
- * @returns The expanded string.
75
- *
76
- * @example
77
- * ```ts
78
- * process.env.FOO = 'bar';
79
- * dotenvExpand('Hello $FOO'); // "Hello bar"
80
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
81
- * ```
82
- *
83
- * @remarks
84
- * The expansion is recursive. If a referenced variable itself contains
85
- * references, those will also be expanded until a stable value is reached.
86
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
87
- */
88
- const dotenvExpand = (value, ref = process.env) => {
89
- const result = interpolate(value, ref);
90
- return result ? result.replace(/\\\$/g, '$') : undefined;
91
- };
92
- /**
93
- * Recursively expands environment variables in the values of a JSON object.
94
- * Variables may be presented with optional default as `$VAR[:default]` or
95
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
96
- *
97
- * @param values - The values object to expand.
98
- * @param options - Expansion options.
99
- * @returns The value object with expanded string values.
100
- *
101
- * @example
102
- * ```ts
103
- * process.env.FOO = 'bar';
104
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
105
- * // => { A: "bar", B: "xbary" }
106
- * ```
107
- *
108
- * @remarks
109
- * Options:
110
- * - ref: The reference object to use for expansion (defaults to process.env).
111
- * - progressive: Whether to progressively add expanded values to the set of
112
- * reference keys.
113
- *
114
- * When `progressive` is true, each expanded key becomes available for
115
- * subsequent expansions in the same object (left-to-right by object key order).
116
- */
117
- function dotenvExpandAll(values, options = {}) {
118
- const { ref = process.env, progressive = false, } = options;
119
- const out = Object.keys(values).reduce((acc, key) => {
120
- acc[key] = dotenvExpand(values[key], {
121
- ...ref,
122
- ...(progressive ? acc : {}),
123
- });
124
- return acc;
125
- }, {});
126
- // Key-preserving return with a permissive index signature to allow later additions.
127
- return out;
128
- }
129
-
130
- const importDefault = async (fileUrl) => {
131
- const mod = (await import(fileUrl));
132
- return mod.default;
133
- };
134
- const cacheHash = (absPath, mtimeMs) => createHash('sha1')
135
- .update(absPath)
136
- .update(String(mtimeMs))
137
- .digest('hex')
138
- .slice(0, 12);
139
- /**
140
- * Remove older compiled cache files for a given source base name, keeping
141
- * at most `keep` most-recent files. Errors are ignored by design.
142
- */
143
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
144
- try {
145
- const entries = await fs.readdir(cacheDir);
146
- const mine = entries
147
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
148
- .map((f) => path.join(cacheDir, f));
149
- if (mine.length <= keep)
150
- return;
151
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
152
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
153
- const toDelete = stats.slice(keep).map((s) => s.p);
154
- await Promise.all(toDelete.map(async (p) => {
155
- try {
156
- await fs.remove(p);
157
- }
158
- catch {
159
- // best-effort cleanup
160
- }
161
- }));
162
- }
163
- catch {
164
- // best-effort cleanup
165
- }
166
- };
167
- /**
168
- * Load a module default export from a JS/TS file with robust fallbacks.
169
- *
170
- * Behavior by extension:
171
- *
172
- * - `.js`/`.mjs`/`.cjs`: direct dynamic import.
173
- * - `.ts`/`.mts`/`.cts`/`.tsx`:
174
- * - try direct dynamic import (when a TS loader is active),
175
- * - else compile via `esbuild` to a cached `.mjs` file and import,
176
- * - else fallback to `typescript.transpileModule` for simple modules.
177
- *
178
- * @typeParam T - Type of the expected default export.
179
- * @param absPath - Absolute path to the source file.
180
- * @param cacheDirName - Cache subfolder under `.tsbuild/`.
181
- * @returns A `Promise\<T | undefined\>` resolving to the default export (if any).
182
- */
183
- const loadModuleDefault = async (absPath, cacheDirName) => {
184
- const ext = path.extname(absPath).toLowerCase();
185
- const fileUrl = url.pathToFileURL(absPath).toString();
186
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
187
- return importDefault(fileUrl);
188
- }
189
- // Try direct import first (TS loader active)
190
- try {
191
- const dyn = await importDefault(fileUrl);
192
- if (dyn)
193
- return dyn;
194
- }
195
- catch {
196
- /* fall through */
197
- }
198
- const stat = await fs.stat(absPath);
199
- const hash = cacheHash(absPath, stat.mtimeMs);
200
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
201
- await fs.ensureDir(cacheDir);
202
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
203
- // Try esbuild
204
- try {
205
- const esbuild = (await import('esbuild'));
206
- await esbuild.build({
207
- entryPoints: [absPath],
208
- bundle: true,
209
- platform: 'node',
210
- format: 'esm',
211
- target: 'node20',
212
- outfile: cacheFile,
213
- sourcemap: false,
214
- logLevel: 'silent',
215
- });
216
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
217
- // Best-effort: trim older cache files for this source.
218
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
219
- return result;
220
- }
221
- catch {
222
- /* fall through to TS transpile */
223
- }
224
- // TypeScript transpile fallback
225
- try {
226
- const ts = (await import('typescript'));
227
- const code = await fs.readFile(absPath, 'utf-8');
228
- const out = ts.transpileModule(code, {
229
- compilerOptions: {
230
- module: 'ESNext',
231
- target: 'ES2022',
232
- moduleResolution: 'NodeNext',
233
- },
234
- }).outputText;
235
- await fs.writeFile(cacheFile, out, 'utf-8');
236
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
237
- // Best-effort: trim older cache files for this source.
238
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
239
- return result;
240
- }
241
- catch {
242
- // Caller decides final error wording; rethrow for upstream mapping.
243
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
244
- }
245
- };
246
-
247
- /** src/env/dynamic.ts
248
- * Helpers for applying and loading dynamic variables (JS/TS).
249
- *
250
- * Requirements addressed:
251
- * - Single service to apply a dynamic map progressively.
252
- * - Single service to load a JS/TS dynamic module with robust fallbacks (util/loadModuleDefault).
253
- * - Unify error messaging so callers show consistent guidance.
254
- */
255
- /**
256
- * Apply a dynamic map to the target progressively.
257
- * - Functions receive (target, env) and may return string | undefined.
258
- * - Literals are assigned directly (including undefined).
259
- *
260
- * @param target - Mutable target environment to assign into.
261
- * @param map - Dynamic map to apply (functions and/or literal values).
262
- * @param env - Selected environment name (if any) passed through to dynamic functions.
263
- * @returns Nothing.
264
- */
265
- function applyDynamicMap(target, map, env) {
266
- if (!map)
267
- return;
268
- for (const key of Object.keys(map)) {
269
- const val = typeof map[key] === 'function'
270
- ? map[key](target, env)
271
- : map[key];
272
- Object.assign(target, { [key]: val });
273
- }
274
- }
275
- /**
276
- * Load a default-export dynamic map from a JS/TS file and apply it.
277
- * Uses util/loadModuleDefault for robust TS handling (direct import, esbuild,
278
- * typescript.transpile fallback).
279
- *
280
- * Error behavior:
281
- * - On failure to load/compile/evaluate the module, throws a unified message:
282
- * "Unable to load dynamic TypeScript file: <absPath>. Install 'esbuild'..."
283
- *
284
- * @param target - Mutable target environment to assign into.
285
- * @param absPath - Absolute path to the dynamic module file.
286
- * @param env - Selected environment name (if any).
287
- * @param cacheDirName - Cache subdirectory under `.tsbuild/` for compiled artifacts.
288
- * @returns A `Promise\<void\>` which resolves after the module (if present) has been applied.
289
- */
290
- async function loadAndApplyDynamic(target, absPath, env, cacheDirName) {
291
- if (!(await fs.exists(absPath)))
292
- return;
293
- let dyn;
294
- try {
295
- dyn = await loadModuleDefault(absPath, cacheDirName);
296
- }
297
- catch {
298
- // Preserve legacy/clear guidance used by tests and docs.
299
- throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
300
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
301
- }
302
- applyDynamicMap(target, dyn, env);
303
- }
304
-
305
- const applyKv = (current, kv) => {
306
- if (!kv || Object.keys(kv).length === 0)
307
- return current;
308
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
309
- return { ...current, ...expanded };
310
- };
311
- const applyConfigSlice = (current, cfg, env) => {
312
- if (!cfg)
313
- return current;
314
- // kind axis: global then env (env overrides global)
315
- const afterGlobal = applyKv(current, cfg.vars);
316
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
317
- return applyKv(afterGlobal, envKv);
318
- };
319
- function overlayEnv(args) {
320
- const { base, env, configs } = args;
321
- let current = { ...base };
322
- // Source: packaged (public -> local)
323
- current = applyConfigSlice(current, configs.packaged, env);
324
- // Packaged "local" is not expected by policy; if present, honor it.
325
- // We do not have a separate object for packaged.local in sources, keep as-is.
326
- // Source: project (public -> local)
327
- current = applyConfigSlice(current, configs.project?.public, env);
328
- current = applyConfigSlice(current, configs.project?.local, env);
329
- // Programmatic explicit vars (top of static tier)
330
- if ('programmaticVars' in args) {
331
- const toApply = Object.fromEntries(Object.entries(args.programmaticVars).filter(([_k, v]) => typeof v === 'string'));
332
- current = applyKv(current, toApply);
333
- }
334
- return current;
335
- }
336
-
337
- export { applyDynamicMap, loadAndApplyDynamic, overlayEnv };
1
+ export { a as applyDynamicMap, l as loadAndApplyDynamic, o as overlayEnv } from './chunks/overlayEnv-Bqh_kPGA.mjs';
2
+ import 'fs-extra';
3
+ import 'node:path';
4
+ import './chunks/loadModuleDefault-Dj8B3Stt.mjs';
5
+ import 'crypto';
6
+ import 'path';
7
+ import 'url';