@karmaniverous/get-dotenv 5.2.1 → 5.2.2
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/dist/plugins-cmd.cjs +2501 -0
- package/dist/plugins-cmd.d.cts +311 -0
- package/dist/plugins-cmd.d.mts +311 -0
- package/dist/plugins-cmd.d.ts +311 -0
- package/dist/plugins-cmd.mjs +2498 -0
- package/dist/plugins-demo.cjs +330 -0
- package/dist/plugins-demo.d.cts +291 -0
- package/dist/plugins-demo.d.mts +291 -0
- package/dist/plugins-demo.d.ts +291 -0
- package/dist/plugins-demo.mjs +328 -0
- package/package.json +21 -1
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { execa, execaCommand } from 'execa';
|
|
2
|
+
|
|
3
|
+
// Minimal tokenizer for shell-off execution:
|
|
4
|
+
// Splits by whitespace while preserving quoted segments (single or double quotes).
|
|
5
|
+
const tokenize = (command) => {
|
|
6
|
+
const out = [];
|
|
7
|
+
let cur = '';
|
|
8
|
+
let quote = null;
|
|
9
|
+
for (let i = 0; i < command.length; i++) {
|
|
10
|
+
const c = command.charAt(i);
|
|
11
|
+
if (quote) {
|
|
12
|
+
if (c === quote) {
|
|
13
|
+
// Support doubled quotes inside a quoted segment (Windows/PowerShell style):
|
|
14
|
+
// "" -> " and '' -> '
|
|
15
|
+
const next = command.charAt(i + 1);
|
|
16
|
+
if (next === quote) {
|
|
17
|
+
cur += quote;
|
|
18
|
+
i += 1; // skip the second quote
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
// end of quoted segment
|
|
22
|
+
quote = null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
cur += c;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
if (c === '"' || c === "'") {
|
|
31
|
+
quote = c;
|
|
32
|
+
}
|
|
33
|
+
else if (/\s/.test(c)) {
|
|
34
|
+
if (cur) {
|
|
35
|
+
out.push(cur);
|
|
36
|
+
cur = '';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
cur += c;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (cur)
|
|
45
|
+
out.push(cur);
|
|
46
|
+
return out;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const dbg = (...args) => {
|
|
50
|
+
if (process.env.GETDOTENV_DEBUG) {
|
|
51
|
+
// Use stderr to avoid interfering with stdout assertions
|
|
52
|
+
console.error('[getdotenv:run]', ...args);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
// Strip repeated symmetric outer quotes (single or double) until stable.
|
|
56
|
+
// This is safe for argv arrays passed to execa (no quoting needed) and avoids
|
|
57
|
+
// passing quote characters through to Node (e.g., for `node -e "<code>"`).
|
|
58
|
+
// Handles stacked quotes from shells like PowerShell: """code""" -> code.
|
|
59
|
+
const stripOuterQuotes = (s) => {
|
|
60
|
+
let out = s;
|
|
61
|
+
// Repeatedly trim only when the entire string is wrapped in matching quotes.
|
|
62
|
+
// Stop as soon as the ends are asymmetric or no quotes remain.
|
|
63
|
+
while (out.length >= 2) {
|
|
64
|
+
const a = out.charAt(0);
|
|
65
|
+
const b = out.charAt(out.length - 1);
|
|
66
|
+
const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
|
|
67
|
+
if (!symmetric)
|
|
68
|
+
break;
|
|
69
|
+
out = out.slice(1, -1);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
};
|
|
73
|
+
// Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
|
|
74
|
+
// expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
|
|
75
|
+
const sanitizeEnv = (env) => {
|
|
76
|
+
if (!env)
|
|
77
|
+
return undefined;
|
|
78
|
+
const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
|
|
79
|
+
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
|
80
|
+
};
|
|
81
|
+
const runCommand = async (command, shell, opts) => {
|
|
82
|
+
if (shell === false) {
|
|
83
|
+
let file;
|
|
84
|
+
let args = [];
|
|
85
|
+
if (Array.isArray(command)) {
|
|
86
|
+
file = command[0];
|
|
87
|
+
args = command.slice(1).map(stripOuterQuotes);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
const tokens = tokenize(command);
|
|
91
|
+
file = tokens[0];
|
|
92
|
+
args = tokens.slice(1);
|
|
93
|
+
}
|
|
94
|
+
if (!file)
|
|
95
|
+
return 0;
|
|
96
|
+
dbg('exec (plain)', { file, args, stdio: opts.stdio });
|
|
97
|
+
// Build options without injecting undefined properties (exactOptionalPropertyTypes).
|
|
98
|
+
const envSan = sanitizeEnv(opts.env);
|
|
99
|
+
const plainOpts = {};
|
|
100
|
+
if (opts.cwd !== undefined)
|
|
101
|
+
plainOpts.cwd = opts.cwd;
|
|
102
|
+
if (envSan !== undefined)
|
|
103
|
+
plainOpts.env = envSan;
|
|
104
|
+
if (opts.stdio !== undefined)
|
|
105
|
+
plainOpts.stdio = opts.stdio;
|
|
106
|
+
const result = await execa(file, args, plainOpts);
|
|
107
|
+
if (opts.stdio === 'pipe' && result.stdout) {
|
|
108
|
+
process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
|
|
109
|
+
}
|
|
110
|
+
const exit = result?.exitCode;
|
|
111
|
+
dbg('exit (plain)', { exitCode: exit });
|
|
112
|
+
return typeof exit === 'number' ? exit : Number.NaN;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
const commandStr = Array.isArray(command) ? command.join(' ') : command;
|
|
116
|
+
dbg('exec (shell)', {
|
|
117
|
+
shell: typeof shell === 'string' ? shell : 'custom',
|
|
118
|
+
stdio: opts.stdio,
|
|
119
|
+
command: commandStr,
|
|
120
|
+
});
|
|
121
|
+
const envSan = sanitizeEnv(opts.env);
|
|
122
|
+
const shellOpts = { shell };
|
|
123
|
+
if (opts.cwd !== undefined)
|
|
124
|
+
shellOpts.cwd = opts.cwd;
|
|
125
|
+
if (envSan !== undefined)
|
|
126
|
+
shellOpts.env = envSan;
|
|
127
|
+
if (opts.stdio !== undefined)
|
|
128
|
+
shellOpts.stdio = opts.stdio;
|
|
129
|
+
const result = await execaCommand(commandStr, shellOpts);
|
|
130
|
+
const out = result?.stdout;
|
|
131
|
+
if (opts.stdio === 'pipe' && out) {
|
|
132
|
+
process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
|
|
133
|
+
}
|
|
134
|
+
const exit = result?.exitCode;
|
|
135
|
+
dbg('exit (shell)', { exitCode: exit });
|
|
136
|
+
return typeof exit === 'number' ? exit : Number.NaN;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Define a GetDotenv CLI plugin with compositional helpers.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
|
|
145
|
+
* .use(childA)
|
|
146
|
+
* .use(childB);
|
|
147
|
+
*/
|
|
148
|
+
const definePlugin = (spec) => {
|
|
149
|
+
const { children = [], ...rest } = spec;
|
|
150
|
+
const plugin = {
|
|
151
|
+
...rest,
|
|
152
|
+
children: [...children],
|
|
153
|
+
use(child) {
|
|
154
|
+
this.children.push(child);
|
|
155
|
+
return this;
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
return plugin;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Batch services (neutral): resolve command and shell settings.
|
|
163
|
+
* Shared by the generator path and the batch plugin to avoid circular deps.
|
|
164
|
+
*/
|
|
165
|
+
/**
|
|
166
|
+
* Resolve a command string from the {@link Scripts} table.
|
|
167
|
+
* A script may be expressed as a string or an object with a `cmd` property.
|
|
168
|
+
*
|
|
169
|
+
* @param scripts - Optional scripts table.
|
|
170
|
+
* @param command - User-provided command name or string.
|
|
171
|
+
* @returns Resolved command string (falls back to the provided command).
|
|
172
|
+
*/
|
|
173
|
+
const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
|
|
174
|
+
? scripts[command].cmd
|
|
175
|
+
: (scripts?.[command] ?? command);
|
|
176
|
+
/**
|
|
177
|
+
* Resolve the shell setting for a given command:
|
|
178
|
+
* - If the script entry is an object, prefer its `shell` override.
|
|
179
|
+
* - Otherwise use the provided `shell` (string | boolean).
|
|
180
|
+
*
|
|
181
|
+
* @param scripts - Optional scripts table.
|
|
182
|
+
* @param command - User-provided command name or string.
|
|
183
|
+
* @param shell - Global shell preference (string | boolean).
|
|
184
|
+
*/
|
|
185
|
+
const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
|
|
186
|
+
? (scripts[command].shell ?? false)
|
|
187
|
+
: (shell ?? false);
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Demo plugin (educational).
|
|
191
|
+
*
|
|
192
|
+
* Purpose
|
|
193
|
+
* - Showcase how to build a plugin for the GetDotenv CLI host.
|
|
194
|
+
* - Demonstrate:
|
|
195
|
+
* - Accessing the resolved dotenv context (ctx).
|
|
196
|
+
* - Executing child processes with explicit env injection.
|
|
197
|
+
* - Resolving commands via scripts and honoring per-script shell overrides.
|
|
198
|
+
* - Thin adapters: business logic stays minimal; use shared helpers.
|
|
199
|
+
*
|
|
200
|
+
* Key host APIs used:
|
|
201
|
+
* - definePlugin: declare a plugin with setup and optional afterResolve.
|
|
202
|
+
* - cli.ns(name): create a namespaced subcommand under the root CLI.
|
|
203
|
+
* - cli.getCtx(): access \{ optionsResolved, dotenv, plugins?, pluginConfigs? \}.
|
|
204
|
+
*
|
|
205
|
+
* Design notes
|
|
206
|
+
* - We use the shared runCommand() helper so behavior matches the built-in
|
|
207
|
+
* cmd/batch plugins (env sanitization, plain vs shell execution, stdio).
|
|
208
|
+
* - We inject ctx.dotenv into child env explicitly to avoid bleeding prior
|
|
209
|
+
* secrets from process.env when exclusions are set (e.g., --exclude-private).
|
|
210
|
+
* - We resolve scripts and shell using shared helpers to honor overrides:
|
|
211
|
+
* resolveCommand(scripts, input) and resolveShell(scripts, input, shell).
|
|
212
|
+
*
|
|
213
|
+
* Usage (examples)
|
|
214
|
+
* getdotenv demo ctx
|
|
215
|
+
* getdotenv demo run --print APP_SETTING
|
|
216
|
+
* getdotenv demo script echo OK
|
|
217
|
+
* getdotenv --trace demo run --print ENV_SETTING
|
|
218
|
+
*/
|
|
219
|
+
const demoPlugin = () => definePlugin({
|
|
220
|
+
id: 'demo',
|
|
221
|
+
setup(cli) {
|
|
222
|
+
const logger = console;
|
|
223
|
+
const ns = cli
|
|
224
|
+
.ns('demo')
|
|
225
|
+
.description('Educational demo of host/plugin features (context, child exec, scripts/shell)');
|
|
226
|
+
/**
|
|
227
|
+
* demo ctx
|
|
228
|
+
* Print a summary of the current dotenv context.
|
|
229
|
+
*
|
|
230
|
+
* Notes:
|
|
231
|
+
* - The host resolves context once per invocation in a preSubcommand hook
|
|
232
|
+
* (added by enhanceGetDotenvCli.passOptions() in the shipped CLI).
|
|
233
|
+
* - ctx.dotenv contains the final merged values after overlays/dynamics.
|
|
234
|
+
*/
|
|
235
|
+
ns.command('ctx')
|
|
236
|
+
.description('Print a summary of the current dotenv context')
|
|
237
|
+
.action(() => {
|
|
238
|
+
const ctx = cli.getCtx();
|
|
239
|
+
const dotenv = ctx?.dotenv ?? {};
|
|
240
|
+
const keys = Object.keys(dotenv).sort();
|
|
241
|
+
const sample = keys.slice(0, 5);
|
|
242
|
+
logger.log('[demo] Context summary:');
|
|
243
|
+
logger.log(`- keys: ${keys.length.toString()}`);
|
|
244
|
+
logger.log(`- sample keys: ${sample.join(', ') || '(none)'}`);
|
|
245
|
+
logger.log('- tip: use "--trace [keys...]" for per-key diagnostics');
|
|
246
|
+
});
|
|
247
|
+
/**
|
|
248
|
+
* demo run [--print KEY]
|
|
249
|
+
* Execute a small child process that prints a dotenv value.
|
|
250
|
+
*
|
|
251
|
+
* Design:
|
|
252
|
+
* - Use shell-off + argv array to avoid cross-platform quoting pitfalls.
|
|
253
|
+
* - Inject ctx.dotenv explicitly into the child env.
|
|
254
|
+
* - Inherit stdio so output streams live (works well outside CI).
|
|
255
|
+
*
|
|
256
|
+
* Tip:
|
|
257
|
+
* - For deterministic capture in CI, run with "--capture" (or set
|
|
258
|
+
* GETDOTENV_STDIO=pipe). The shipped CLI honors both.
|
|
259
|
+
*/
|
|
260
|
+
ns.command('run')
|
|
261
|
+
.description('Run a small child process under the current dotenv (shell-off)')
|
|
262
|
+
.option('--print <key>', 'dotenv key to print', 'APP_SETTING')
|
|
263
|
+
.action(async (opts) => {
|
|
264
|
+
const key = typeof opts.print === 'string' && opts.print.length > 0
|
|
265
|
+
? opts.print
|
|
266
|
+
: 'APP_SETTING';
|
|
267
|
+
// Build a minimal node -e payload via argv array (avoid quoting issues).
|
|
268
|
+
const code = `console.log(process.env.${key} ?? "")`;
|
|
269
|
+
const ctx = cli.getCtx();
|
|
270
|
+
const dotenv = (ctx?.dotenv ?? {});
|
|
271
|
+
// Inherit stdio for an interactive demo. Use --capture for CI.
|
|
272
|
+
await runCommand(['node', '-e', code], false, {
|
|
273
|
+
env: { ...process.env, ...dotenv },
|
|
274
|
+
stdio: 'inherit',
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
/**
|
|
278
|
+
* demo script [command...]
|
|
279
|
+
* Resolve and execute a command using the current scripts table and
|
|
280
|
+
* shell preference (with per-script overrides).
|
|
281
|
+
*
|
|
282
|
+
* How it works:
|
|
283
|
+
* - We read the merged CLI options persisted by the shipped CLI’s
|
|
284
|
+
* passOptions() hook on the current command instance’s parent.
|
|
285
|
+
* - resolveCommand resolves a script name → cmd or passes through a raw
|
|
286
|
+
* command string.
|
|
287
|
+
* - resolveShell chooses the appropriate shell:
|
|
288
|
+
* scripts[name].shell ?? global shell (string|boolean).
|
|
289
|
+
*/
|
|
290
|
+
ns.command('script')
|
|
291
|
+
.description('Resolve a command via scripts and execute it with the proper shell')
|
|
292
|
+
.argument('[command...]')
|
|
293
|
+
.action(async (commandParts, _opts, thisCommand) => {
|
|
294
|
+
// Safely access the parent’s merged options (installed by passOptions()).
|
|
295
|
+
const parent = thisCommand.parent;
|
|
296
|
+
const bag = (parent?.getDotenvCliOptions ?? {});
|
|
297
|
+
const input = Array.isArray(commandParts)
|
|
298
|
+
? commandParts.map(String).join(' ')
|
|
299
|
+
: '';
|
|
300
|
+
if (!input) {
|
|
301
|
+
logger.log('[demo] Please provide a command or script name, e.g. "echo OK" or "git-status".');
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const resolved = resolveCommand(bag?.scripts, input);
|
|
305
|
+
const shell = resolveShell(bag?.scripts, input, bag?.shell);
|
|
306
|
+
// Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
|
|
307
|
+
const ctx = cli.getCtx();
|
|
308
|
+
const dotenv = (ctx?.dotenv ?? {});
|
|
309
|
+
await runCommand(resolved, shell, {
|
|
310
|
+
env: { ...process.env, ...dotenv },
|
|
311
|
+
stdio: 'inherit',
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
},
|
|
315
|
+
/**
|
|
316
|
+
* Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
|
|
317
|
+
* For the demo we just log once to hint where such logic would live.
|
|
318
|
+
*/
|
|
319
|
+
afterResolve(_cli, ctx) {
|
|
320
|
+
const keys = Object.keys(ctx.dotenv);
|
|
321
|
+
if (keys.length > 0) {
|
|
322
|
+
// Keep noise low; a single-line breadcrumb is sufficient for the demo.
|
|
323
|
+
console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
export { demoPlugin };
|
package/package.json
CHANGED
|
@@ -120,6 +120,26 @@
|
|
|
120
120
|
"default": "./dist/plugins-init.cjs"
|
|
121
121
|
}
|
|
122
122
|
},
|
|
123
|
+
"./plugins/cmd": {
|
|
124
|
+
"import": {
|
|
125
|
+
"types": "./dist/plugins-cmd.d.mts",
|
|
126
|
+
"default": "./dist/plugins-cmd.mjs"
|
|
127
|
+
},
|
|
128
|
+
"require": {
|
|
129
|
+
"types": "./dist/plugins-cmd.d.cts",
|
|
130
|
+
"default": "./dist/plugins-cmd.cjs"
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
"./plugins/demo": {
|
|
134
|
+
"import": {
|
|
135
|
+
"types": "./dist/plugins-demo.d.mts",
|
|
136
|
+
"default": "./dist/plugins-demo.mjs"
|
|
137
|
+
},
|
|
138
|
+
"require": {
|
|
139
|
+
"types": "./dist/plugins-demo.d.cts",
|
|
140
|
+
"default": "./dist/plugins-demo.cjs"
|
|
141
|
+
}
|
|
142
|
+
},
|
|
123
143
|
"./config": {
|
|
124
144
|
"import": {
|
|
125
145
|
"types": "./dist/config.d.mts",
|
|
@@ -225,5 +245,5 @@
|
|
|
225
245
|
},
|
|
226
246
|
"type": "module",
|
|
227
247
|
"types": "dist/index.d.ts",
|
|
228
|
-
"version": "5.2.
|
|
248
|
+
"version": "5.2.2"
|
|
229
249
|
}
|