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