@karmaniverous/get-dotenv 6.0.0-1 → 6.1.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 +91 -379
- package/dist/cli.d.ts +569 -0
- package/dist/cli.mjs +18877 -0
- package/dist/cliHost.d.ts +528 -184
- package/dist/cliHost.mjs +1977 -1428
- package/dist/config.d.ts +191 -14
- package/dist/config.mjs +266 -81
- package/dist/env-overlay.d.ts +223 -16
- package/dist/env-overlay.mjs +185 -4
- package/dist/getdotenv.cli.mjs +18025 -3196
- package/dist/index.d.ts +623 -256
- package/dist/index.mjs +18045 -3206
- package/dist/plugins-aws.d.ts +221 -91
- package/dist/plugins-aws.mjs +2411 -369
- package/dist/plugins-batch.d.ts +300 -103
- package/dist/plugins-batch.mjs +2560 -484
- package/dist/plugins-cmd.d.ts +229 -106
- package/dist/plugins-cmd.mjs +2518 -790
- package/dist/plugins-init.d.ts +221 -95
- package/dist/plugins-init.mjs +2170 -105
- package/dist/plugins.d.ts +246 -125
- package/dist/plugins.mjs +17941 -1968
- package/dist/templates/cli/index.ts +25 -0
- package/{templates/cli/ts → dist/templates/cli}/plugins/hello.ts +13 -9
- 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 +42 -0
- package/dist/templates/index.ts +25 -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 +42 -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 +42 -39
- package/templates/cli/index.ts +25 -0
- package/templates/cli/plugins/hello.ts +42 -0
- package/templates/config/js/getdotenv.config.js +8 -3
- 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 +8 -3
- package/templates/config/yaml/public/getdotenv.config.yaml +0 -3
- package/dist/plugins-demo.d.ts +0 -204
- package/dist/plugins-demo.mjs +0 -496
- package/templates/cli/ts/index.ts +0 -9
package/dist/plugins-demo.mjs
DELETED
|
@@ -1,496 +0,0 @@
|
|
|
1
|
-
import { execa, execaCommand } from 'execa';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import 'fs-extra';
|
|
4
|
-
import 'path';
|
|
5
|
-
import 'package-directory';
|
|
6
|
-
import 'url';
|
|
7
|
-
import 'yaml';
|
|
8
|
-
import 'nanoid';
|
|
9
|
-
import 'dotenv';
|
|
10
|
-
import 'crypto';
|
|
11
|
-
|
|
12
|
-
// Minimal tokenizer for shell-off execution:
|
|
13
|
-
// Splits by whitespace while preserving quoted segments (single or double quotes).
|
|
14
|
-
// Optionally preserve doubled quotes inside quoted segments:
|
|
15
|
-
// - default: "" => " (Windows/PowerShell style literal-quote escape)
|
|
16
|
-
// - preserveDoubledQuotes: true => "" stays "" (needed for Node -e payloads)
|
|
17
|
-
const tokenize = (command, opts) => {
|
|
18
|
-
const out = [];
|
|
19
|
-
let cur = '';
|
|
20
|
-
let quote = null;
|
|
21
|
-
for (let i = 0; i < command.length; i++) {
|
|
22
|
-
const c = command.charAt(i);
|
|
23
|
-
if (quote) {
|
|
24
|
-
if (c === quote) {
|
|
25
|
-
// Support doubled quotes inside a quoted segment:
|
|
26
|
-
// default: "" -> " and '' -> ' (Windows/PowerShell style)
|
|
27
|
-
// preserve: keep as "" to allow empty string literals in Node -e payloads
|
|
28
|
-
const next = command.charAt(i + 1);
|
|
29
|
-
if (next === quote) {
|
|
30
|
-
{
|
|
31
|
-
// Collapse to a single literal quote
|
|
32
|
-
cur += quote;
|
|
33
|
-
i += 1; // skip the second quote
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
// end of quoted segment
|
|
38
|
-
quote = null;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
else {
|
|
42
|
-
cur += c;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
else {
|
|
46
|
-
if (c === '"' || c === "'") {
|
|
47
|
-
quote = c;
|
|
48
|
-
}
|
|
49
|
-
else if (/\s/.test(c)) {
|
|
50
|
-
if (cur) {
|
|
51
|
-
out.push(cur);
|
|
52
|
-
cur = '';
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
else {
|
|
56
|
-
cur += c;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
if (cur)
|
|
61
|
-
out.push(cur);
|
|
62
|
-
return out;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const dbg = (...args) => {
|
|
66
|
-
if (process.env.GETDOTENV_DEBUG) {
|
|
67
|
-
// Use stderr to avoid interfering with stdout assertions
|
|
68
|
-
console.error('[getdotenv:run]', ...args);
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
// Strip repeated symmetric outer quotes (single or double) until stable.
|
|
72
|
-
// This is safe for argv arrays passed to execa (no quoting needed) and avoids
|
|
73
|
-
// passing quote characters through to Node (e.g., for `node -e "<code>"`).
|
|
74
|
-
// Handles stacked quotes from shells like PowerShell: """code""" -> code.
|
|
75
|
-
const stripOuterQuotes = (s) => {
|
|
76
|
-
let out = s;
|
|
77
|
-
// Repeatedly trim only when the entire string is wrapped in matching quotes.
|
|
78
|
-
// Stop as soon as the ends are asymmetric or no quotes remain.
|
|
79
|
-
while (out.length >= 2) {
|
|
80
|
-
const a = out.charAt(0);
|
|
81
|
-
const b = out.charAt(out.length - 1);
|
|
82
|
-
const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
|
|
83
|
-
if (!symmetric)
|
|
84
|
-
break;
|
|
85
|
-
out = out.slice(1, -1);
|
|
86
|
-
}
|
|
87
|
-
return out;
|
|
88
|
-
};
|
|
89
|
-
// Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
|
|
90
|
-
const pickResult = (r) => {
|
|
91
|
-
const exit = r.exitCode;
|
|
92
|
-
const stdoutVal = r.stdout;
|
|
93
|
-
const stderrVal = r.stderr;
|
|
94
|
-
return {
|
|
95
|
-
exitCode: typeof exit === 'number' ? exit : Number.NaN,
|
|
96
|
-
stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
|
|
97
|
-
stderr: typeof stderrVal === 'string' ? stderrVal : '',
|
|
98
|
-
};
|
|
99
|
-
};
|
|
100
|
-
// Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
|
|
101
|
-
// expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
|
|
102
|
-
const sanitizeEnv = (env) => {
|
|
103
|
-
if (!env)
|
|
104
|
-
return undefined;
|
|
105
|
-
const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
|
|
106
|
-
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
|
107
|
-
};
|
|
108
|
-
async function runCommand(command, shell, opts) {
|
|
109
|
-
if (shell === false) {
|
|
110
|
-
let file;
|
|
111
|
-
let args = [];
|
|
112
|
-
if (typeof command === 'string') {
|
|
113
|
-
const tokens = tokenize(command);
|
|
114
|
-
file = tokens[0];
|
|
115
|
-
args = tokens.slice(1);
|
|
116
|
-
}
|
|
117
|
-
else {
|
|
118
|
-
file = command[0];
|
|
119
|
-
args = command.slice(1).map(stripOuterQuotes);
|
|
120
|
-
}
|
|
121
|
-
if (!file)
|
|
122
|
-
return 0;
|
|
123
|
-
dbg('exec (plain)', { file, args, stdio: opts.stdio });
|
|
124
|
-
// Build options without injecting undefined properties (exactOptionalPropertyTypes).
|
|
125
|
-
const envSan = sanitizeEnv(opts.env);
|
|
126
|
-
const plainOpts = {};
|
|
127
|
-
if (opts.cwd !== undefined)
|
|
128
|
-
plainOpts.cwd = opts.cwd;
|
|
129
|
-
if (envSan !== undefined)
|
|
130
|
-
plainOpts.env = envSan;
|
|
131
|
-
if (opts.stdio !== undefined)
|
|
132
|
-
plainOpts.stdio = opts.stdio;
|
|
133
|
-
const ok = pickResult((await execa(file, args, plainOpts)));
|
|
134
|
-
if (opts.stdio === 'pipe' && ok.stdout) {
|
|
135
|
-
process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
|
|
136
|
-
}
|
|
137
|
-
dbg('exit (plain)', { exitCode: ok.exitCode });
|
|
138
|
-
return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
|
|
139
|
-
}
|
|
140
|
-
else {
|
|
141
|
-
const commandStr = typeof command === 'string' ? command : command.join(' ');
|
|
142
|
-
dbg('exec (shell)', {
|
|
143
|
-
shell: typeof shell === 'string' ? shell : 'custom',
|
|
144
|
-
stdio: opts.stdio,
|
|
145
|
-
command: commandStr,
|
|
146
|
-
});
|
|
147
|
-
const envSan = sanitizeEnv(opts.env);
|
|
148
|
-
const shellOpts = { shell };
|
|
149
|
-
if (opts.cwd !== undefined)
|
|
150
|
-
shellOpts.cwd = opts.cwd;
|
|
151
|
-
if (envSan !== undefined)
|
|
152
|
-
shellOpts.env = envSan;
|
|
153
|
-
if (opts.stdio !== undefined)
|
|
154
|
-
shellOpts.stdio = opts.stdio;
|
|
155
|
-
const ok = pickResult((await execaCommand(commandStr, shellOpts)));
|
|
156
|
-
if (opts.stdio === 'pipe' && ok.stdout) {
|
|
157
|
-
process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
|
|
158
|
-
}
|
|
159
|
-
dbg('exit (shell)', { exitCode: ok.exitCode });
|
|
160
|
-
return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/** src/cliCore/spawnEnv.ts
|
|
165
|
-
* Build a sanitized environment bag for child processes.
|
|
166
|
-
*
|
|
167
|
-
* Requirements addressed:
|
|
168
|
-
* - Provide a single helper (buildSpawnEnv) to normalize/dedupe child env.
|
|
169
|
-
* - Drop undefined values (exactOptional semantics).
|
|
170
|
-
* - On Windows, dedupe keys case-insensitively and prefer the last value,
|
|
171
|
-
* preserving the latest key's casing. Ensure HOME fallback from USERPROFILE.
|
|
172
|
-
* Normalize TMP/TEMP consistency when either is present.
|
|
173
|
-
* - On POSIX, keep keys as-is; when a temp dir key is present (TMPDIR/TMP/TEMP),
|
|
174
|
-
* ensure TMPDIR exists for downstream consumers that expect it.
|
|
175
|
-
*
|
|
176
|
-
* Adapter responsibility: pure mapping; no business logic.
|
|
177
|
-
*/
|
|
178
|
-
const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
|
|
179
|
-
/** Build a sanitized env for child processes from base + overlay. */
|
|
180
|
-
const buildSpawnEnv = (base, overlay) => {
|
|
181
|
-
const raw = {
|
|
182
|
-
...(base ?? {}),
|
|
183
|
-
...(overlay ?? {}),
|
|
184
|
-
};
|
|
185
|
-
// Drop undefined first
|
|
186
|
-
const entries = Object.entries(dropUndefined(raw));
|
|
187
|
-
if (process.platform === 'win32') {
|
|
188
|
-
// Windows: keys are case-insensitive; collapse duplicates
|
|
189
|
-
const byLower = new Map();
|
|
190
|
-
for (const [k, v] of entries) {
|
|
191
|
-
byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
|
|
192
|
-
}
|
|
193
|
-
const out = {};
|
|
194
|
-
for (const [, [k, v]] of byLower)
|
|
195
|
-
out[k] = v;
|
|
196
|
-
// HOME fallback from USERPROFILE (common expectation)
|
|
197
|
-
if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
|
|
198
|
-
const up = out['USERPROFILE'];
|
|
199
|
-
if (typeof up === 'string' && up.length > 0)
|
|
200
|
-
out['HOME'] = up;
|
|
201
|
-
}
|
|
202
|
-
// Normalize TMP/TEMP coherence (pick any present; reflect to both)
|
|
203
|
-
const tmp = out['TMP'] ?? out['TEMP'];
|
|
204
|
-
if (typeof tmp === 'string' && tmp.length > 0) {
|
|
205
|
-
out['TMP'] = tmp;
|
|
206
|
-
out['TEMP'] = tmp;
|
|
207
|
-
}
|
|
208
|
-
return out;
|
|
209
|
-
}
|
|
210
|
-
// POSIX: keep keys as-is
|
|
211
|
-
const out = Object.fromEntries(entries);
|
|
212
|
-
// Ensure TMPDIR exists when any temp key is present (best-effort)
|
|
213
|
-
const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
|
|
214
|
-
if (typeof tmpdir === 'string' && tmpdir.length > 0) {
|
|
215
|
-
out['TMPDIR'] = tmpdir;
|
|
216
|
-
}
|
|
217
|
-
return out;
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* Zod schemas for configuration files discovered by the new loader.
|
|
222
|
-
*
|
|
223
|
-
* Notes:
|
|
224
|
-
* - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
|
|
225
|
-
* - RESOLVED: normalized shapes (paths always string[]).
|
|
226
|
-
* - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
|
|
227
|
-
*/
|
|
228
|
-
// String-only env value map
|
|
229
|
-
const stringMap = z.record(z.string(), z.string());
|
|
230
|
-
const envStringMap = z.record(z.string(), stringMap);
|
|
231
|
-
// Allow string[] or single string for "paths" in RAW; normalize later.
|
|
232
|
-
const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
|
|
233
|
-
const getDotenvConfigSchemaRaw = z.object({
|
|
234
|
-
dotenvToken: z.string().optional(),
|
|
235
|
-
privateToken: z.string().optional(),
|
|
236
|
-
paths: rawPathsSchema,
|
|
237
|
-
loadProcess: z.boolean().optional(),
|
|
238
|
-
log: z.boolean().optional(),
|
|
239
|
-
shell: z.union([z.string(), z.boolean()]).optional(),
|
|
240
|
-
scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
|
|
241
|
-
requiredKeys: z.array(z.string()).optional(),
|
|
242
|
-
schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
|
|
243
|
-
vars: stringMap.optional(), // public, global
|
|
244
|
-
envVars: envStringMap.optional(), // public, per-env
|
|
245
|
-
// Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
|
|
246
|
-
dynamic: z.unknown().optional(),
|
|
247
|
-
// Per-plugin config bag; validated by plugins/host when used.
|
|
248
|
-
plugins: z.record(z.string(), z.unknown()).optional(),
|
|
249
|
-
});
|
|
250
|
-
// Normalize paths to string[]
|
|
251
|
-
const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
|
|
252
|
-
getDotenvConfigSchemaRaw.transform((raw) => ({
|
|
253
|
-
...raw,
|
|
254
|
-
paths: normalizePaths(raw.paths),
|
|
255
|
-
}));
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Zod schemas for programmatic GetDotenv options.
|
|
259
|
-
*
|
|
260
|
-
* Canonical source of truth for options shape. Public types are derived
|
|
261
|
-
* from these schemas (see consumers via z.output\<\>).
|
|
262
|
-
*/
|
|
263
|
-
// Minimal process env representation: string values or undefined to indicate "unset".
|
|
264
|
-
const processEnvSchema = z.record(z.string(), z.string().optional());
|
|
265
|
-
// RAW: all fields optional — undefined means "inherit" from lower layers.
|
|
266
|
-
z.object({
|
|
267
|
-
defaultEnv: z.string().optional(),
|
|
268
|
-
dotenvToken: z.string().optional(),
|
|
269
|
-
dynamicPath: z.string().optional(),
|
|
270
|
-
// Dynamic map is intentionally wide for now; refine once sources are normalized.
|
|
271
|
-
dynamic: z.record(z.string(), z.unknown()).optional(),
|
|
272
|
-
env: z.string().optional(),
|
|
273
|
-
excludeDynamic: z.boolean().optional(),
|
|
274
|
-
excludeEnv: z.boolean().optional(),
|
|
275
|
-
excludeGlobal: z.boolean().optional(),
|
|
276
|
-
excludePrivate: z.boolean().optional(),
|
|
277
|
-
excludePublic: z.boolean().optional(),
|
|
278
|
-
loadProcess: z.boolean().optional(),
|
|
279
|
-
log: z.boolean().optional(),
|
|
280
|
-
logger: z.unknown().optional(),
|
|
281
|
-
outputPath: z.string().optional(),
|
|
282
|
-
paths: z.array(z.string()).optional(),
|
|
283
|
-
privateToken: z.string().optional(),
|
|
284
|
-
vars: processEnvSchema.optional(),
|
|
285
|
-
});
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* Instance-bound plugin config store.
|
|
289
|
-
* Host stores the validated/interpolated slice per plugin instance.
|
|
290
|
-
* The store is intentionally private to this module; definePlugin()
|
|
291
|
-
* provides a typed accessor that reads from this store for the calling
|
|
292
|
-
* plugin instance.
|
|
293
|
-
*/
|
|
294
|
-
const PLUGIN_CONFIG_STORE = new WeakMap();
|
|
295
|
-
const _getPluginConfigForInstance = (plugin) => PLUGIN_CONFIG_STORE.get(plugin);
|
|
296
|
-
|
|
297
|
-
/** src/cliHost/definePlugin.ts
|
|
298
|
-
* Plugin contracts for the GetDotenv CLI host.
|
|
299
|
-
*
|
|
300
|
-
* This module exposes a structural public interface for the host that plugins
|
|
301
|
-
* should use (GetDotenvCliPublic). Using a structural type at the seam avoids
|
|
302
|
-
* nominal class identity issues (private fields) in downstream consumers.
|
|
303
|
-
*/
|
|
304
|
-
/* eslint-disable tsdoc/syntax */
|
|
305
|
-
function definePlugin(spec) {
|
|
306
|
-
const { children = [], ...rest } = spec;
|
|
307
|
-
// Default to a strict empty-object schema so “no-config” plugins fail fast
|
|
308
|
-
// on unknown keys and provide a concrete {} at runtime.
|
|
309
|
-
const effectiveSchema = spec.configSchema ?? z.object({}).strict();
|
|
310
|
-
// Build base plugin first, then extend with instance-bound helpers.
|
|
311
|
-
const base = {
|
|
312
|
-
...rest,
|
|
313
|
-
// Always carry a schema (strict empty by default) to simplify host logic
|
|
314
|
-
// and improve inference/ergonomics for plugin authors.
|
|
315
|
-
configSchema: effectiveSchema,
|
|
316
|
-
children: [...children],
|
|
317
|
-
use(child) {
|
|
318
|
-
this.children.push(child);
|
|
319
|
-
return this;
|
|
320
|
-
},
|
|
321
|
-
};
|
|
322
|
-
// Attach instance-bound helpers on the returned plugin object.
|
|
323
|
-
const extended = base;
|
|
324
|
-
extended.readConfig = function (_cli) {
|
|
325
|
-
// Config is stored per-plugin-instance by the host (WeakMap in computeContext).
|
|
326
|
-
const value = _getPluginConfigForInstance(extended);
|
|
327
|
-
if (value === undefined) {
|
|
328
|
-
// Guard: host has not resolved config yet (incorrect lifecycle usage).
|
|
329
|
-
throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
|
|
330
|
-
}
|
|
331
|
-
return value;
|
|
332
|
-
};
|
|
333
|
-
// Plugin-bound dynamic option factory
|
|
334
|
-
extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
|
|
335
|
-
return cli.createDynamicOption(flags, (cfg) => {
|
|
336
|
-
// Prefer the validated slice stored per instance; fallback to help-bag
|
|
337
|
-
// (by-id) so top-level `-h` can render effective defaults before resolve.
|
|
338
|
-
const fromStore = _getPluginConfigForInstance(extended);
|
|
339
|
-
const id = extended.id;
|
|
340
|
-
let fromBag;
|
|
341
|
-
if (!fromStore && id) {
|
|
342
|
-
const maybe = cfg.plugins[id];
|
|
343
|
-
if (maybe && typeof maybe === 'object') {
|
|
344
|
-
fromBag = maybe;
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
// Always provide a concrete object to dynamic callbacks:
|
|
348
|
-
// - With a schema: computeContext stores the parsed object.
|
|
349
|
-
// - Without a schema: computeContext stores {}.
|
|
350
|
-
// - Help-time fallback: coalesce to {} when only a by-id bag exists.
|
|
351
|
-
const cfgVal = (fromStore ?? fromBag ?? {});
|
|
352
|
-
return desc(cfg, cfgVal);
|
|
353
|
-
}, parser, defaultValue);
|
|
354
|
-
};
|
|
355
|
-
return extended;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
/**
|
|
359
|
-
* Batch services (neutral): resolve command and shell settings.
|
|
360
|
-
* Shared by the generator path and the batch plugin to avoid circular deps.
|
|
361
|
-
*/
|
|
362
|
-
/**
|
|
363
|
-
* Resolve a command string from the {@link Scripts} table.
|
|
364
|
-
* A script may be expressed as a string or an object with a `cmd` property.
|
|
365
|
-
*
|
|
366
|
-
* @param scripts - Optional scripts table.
|
|
367
|
-
* @param command - User-provided command name or string.
|
|
368
|
-
* @returns Resolved command string (falls back to the provided command).
|
|
369
|
-
*/
|
|
370
|
-
const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
|
|
371
|
-
? scripts[command].cmd
|
|
372
|
-
: (scripts?.[command] ?? command);
|
|
373
|
-
/**
|
|
374
|
-
* Resolve the shell setting for a given command:
|
|
375
|
-
* - If the script entry is an object, prefer its `shell` override.
|
|
376
|
-
* - Otherwise use the provided `shell` (string | boolean).
|
|
377
|
-
*
|
|
378
|
-
* @param scripts - Optional scripts table.
|
|
379
|
-
* @param command - User-provided command name or string.
|
|
380
|
-
* @param shell - Global shell preference (string | boolean).
|
|
381
|
-
*/
|
|
382
|
-
const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
|
|
383
|
-
? (scripts[command].shell ?? false)
|
|
384
|
-
: (shell ?? false);
|
|
385
|
-
|
|
386
|
-
const demoPlugin = () => definePlugin({
|
|
387
|
-
id: 'demo',
|
|
388
|
-
setup(cli) {
|
|
389
|
-
const logger = console;
|
|
390
|
-
const ns = cli
|
|
391
|
-
.ns('demo')
|
|
392
|
-
.description('Educational demo of host/plugin features (context, child exec, scripts/shell)');
|
|
393
|
-
/**
|
|
394
|
-
* demo ctx
|
|
395
|
-
* Print a summary of the current dotenv context.
|
|
396
|
-
*
|
|
397
|
-
* Notes:
|
|
398
|
-
* - The host resolves context once per invocation in a preSubcommand hook
|
|
399
|
-
* (added by enhanceGetDotenvCli.passOptions() in the shipped CLI).
|
|
400
|
-
* - ctx.dotenv contains the final merged values after overlays/dynamics.
|
|
401
|
-
*/
|
|
402
|
-
ns.command('ctx')
|
|
403
|
-
.description('Print a summary of the current dotenv context')
|
|
404
|
-
.action(() => {
|
|
405
|
-
const ctx = cli.getCtx();
|
|
406
|
-
const dotenv = ctx?.dotenv ?? {};
|
|
407
|
-
const keys = Object.keys(dotenv).sort();
|
|
408
|
-
const sample = keys.slice(0, 5);
|
|
409
|
-
logger.log('[demo] Context summary:');
|
|
410
|
-
logger.log(`- keys: ${keys.length.toString()}`);
|
|
411
|
-
logger.log(`- sample keys: ${sample.join(', ') || '(none)'}`);
|
|
412
|
-
logger.log('- tip: use "--trace [keys...]" for per-key diagnostics');
|
|
413
|
-
});
|
|
414
|
-
/**
|
|
415
|
-
* demo run [--print KEY]
|
|
416
|
-
* Execute a small child process that prints a dotenv value.
|
|
417
|
-
*
|
|
418
|
-
* Design:
|
|
419
|
-
* - Use shell-off + argv array to avoid cross-platform quoting pitfalls.
|
|
420
|
-
* - Inject ctx.dotenv explicitly into the child env.
|
|
421
|
-
* - Inherit stdio so output streams live (works well outside CI).
|
|
422
|
-
*
|
|
423
|
-
* Tip:
|
|
424
|
-
* - For deterministic capture in CI, run with "--capture" (or set
|
|
425
|
-
* GETDOTENV_STDIO=pipe). The shipped CLI honors both.
|
|
426
|
-
*/
|
|
427
|
-
ns.command('run')
|
|
428
|
-
.description('Run a small child process under the current dotenv (shell-off)')
|
|
429
|
-
.option('--print <key>', 'dotenv key to print', 'APP_SETTING')
|
|
430
|
-
.action(async (opts) => {
|
|
431
|
-
const key = typeof opts.print === 'string' && opts.print.length > 0
|
|
432
|
-
? opts.print
|
|
433
|
-
: 'APP_SETTING';
|
|
434
|
-
// Build a minimal node -e payload via argv array (avoid quoting issues).
|
|
435
|
-
const code = `console.log(process.env.${key} ?? "")`;
|
|
436
|
-
const ctx = cli.getCtx();
|
|
437
|
-
// Inherit stdio for an interactive demo. Use --capture for CI.
|
|
438
|
-
await runCommand(['node', '-e', code], false, {
|
|
439
|
-
env: buildSpawnEnv(process.env, ctx?.dotenv),
|
|
440
|
-
stdio: 'inherit',
|
|
441
|
-
});
|
|
442
|
-
});
|
|
443
|
-
/**
|
|
444
|
-
* demo script [command...]
|
|
445
|
-
* Resolve and execute a command using the current scripts table and
|
|
446
|
-
* shell preference (with per-script overrides).
|
|
447
|
-
*
|
|
448
|
-
* How it works:
|
|
449
|
-
* - We read the merged CLI options persisted by the shipped CLI’s
|
|
450
|
-
* passOptions() hook on the current command instance’s parent.
|
|
451
|
-
* - resolveCommand resolves a script name → cmd or passes through a raw
|
|
452
|
-
* command string.
|
|
453
|
-
* - resolveShell chooses the appropriate shell:
|
|
454
|
-
* scripts[name].shell ?? global shell (string|boolean).
|
|
455
|
-
*/
|
|
456
|
-
ns.command('script')
|
|
457
|
-
.description('Resolve a command via scripts and execute it with the proper shell')
|
|
458
|
-
.argument('[command...]')
|
|
459
|
-
.action(async (commandParts, _opts, thisCommand) => {
|
|
460
|
-
// Safely access the parent’s merged options (installed by passOptions()).
|
|
461
|
-
const parent = thisCommand.parent;
|
|
462
|
-
const bag = (parent?.getDotenvCliOptions ?? {});
|
|
463
|
-
const input = Array.isArray(commandParts)
|
|
464
|
-
? commandParts.map(String).join(' ')
|
|
465
|
-
: '';
|
|
466
|
-
if (!input) {
|
|
467
|
-
logger.log('[demo] Please provide a command or script name, e.g. "echo OK" or "git-status".');
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
const resolved = resolveCommand(bag?.scripts, input);
|
|
471
|
-
const shell = resolveShell(bag?.scripts, input, bag?.shell);
|
|
472
|
-
// Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
|
|
473
|
-
const ctx = cli.getCtx();
|
|
474
|
-
await runCommand(resolved, shell, {
|
|
475
|
-
env: buildSpawnEnv(process.env, ctx?.dotenv),
|
|
476
|
-
stdio: 'inherit',
|
|
477
|
-
});
|
|
478
|
-
});
|
|
479
|
-
},
|
|
480
|
-
/**
|
|
481
|
-
* Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
|
|
482
|
-
* For the demo we emit a single breadcrumb only when GETDOTENV_DEBUG is set,
|
|
483
|
-
* keeping default runs (tests/CI/smoke) quiet.
|
|
484
|
-
*/
|
|
485
|
-
afterResolve(_cli, ctx) {
|
|
486
|
-
if (process.env.GETDOTENV_DEBUG) {
|
|
487
|
-
const keys = Object.keys(ctx.dotenv);
|
|
488
|
-
if (keys.length > 0) {
|
|
489
|
-
// Keep noise low; a single-line breadcrumb is sufficient for the demo.
|
|
490
|
-
console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
},
|
|
494
|
-
});
|
|
495
|
-
|
|
496
|
-
export { demoPlugin };
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { GetDotenvCli } from '@karmaniverous/get-dotenv/cliHost';
|
|
2
|
-
import type { Command } from 'commander';
|
|
3
|
-
|
|
4
|
-
import { helloPlugin } from './plugins/hello';
|
|
5
|
-
|
|
6
|
-
const program: Command = new GetDotenvCli('__CLI_NAME__').use(helloPlugin());
|
|
7
|
-
|
|
8
|
-
await (program as unknown as GetDotenvCli).resolveAndLoad();
|
|
9
|
-
await program.parseAsync();
|