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