@karmaniverous/get-dotenv 5.2.1 → 5.2.3

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.
@@ -0,0 +1,298 @@
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
+ const demoPlugin = () => definePlugin({
190
+ id: 'demo',
191
+ setup(cli) {
192
+ const logger = console;
193
+ const ns = cli
194
+ .ns('demo')
195
+ .description('Educational demo of host/plugin features (context, child exec, scripts/shell)');
196
+ /**
197
+ * demo ctx
198
+ * Print a summary of the current dotenv context.
199
+ *
200
+ * Notes:
201
+ * - The host resolves context once per invocation in a preSubcommand hook
202
+ * (added by enhanceGetDotenvCli.passOptions() in the shipped CLI).
203
+ * - ctx.dotenv contains the final merged values after overlays/dynamics.
204
+ */
205
+ ns.command('ctx')
206
+ .description('Print a summary of the current dotenv context')
207
+ .action(() => {
208
+ const ctx = cli.getCtx();
209
+ const dotenv = ctx?.dotenv ?? {};
210
+ const keys = Object.keys(dotenv).sort();
211
+ const sample = keys.slice(0, 5);
212
+ logger.log('[demo] Context summary:');
213
+ logger.log(`- keys: ${keys.length.toString()}`);
214
+ logger.log(`- sample keys: ${sample.join(', ') || '(none)'}`);
215
+ logger.log('- tip: use "--trace [keys...]" for per-key diagnostics');
216
+ });
217
+ /**
218
+ * demo run [--print KEY]
219
+ * Execute a small child process that prints a dotenv value.
220
+ *
221
+ * Design:
222
+ * - Use shell-off + argv array to avoid cross-platform quoting pitfalls.
223
+ * - Inject ctx.dotenv explicitly into the child env.
224
+ * - Inherit stdio so output streams live (works well outside CI).
225
+ *
226
+ * Tip:
227
+ * - For deterministic capture in CI, run with "--capture" (or set
228
+ * GETDOTENV_STDIO=pipe). The shipped CLI honors both.
229
+ */
230
+ ns.command('run')
231
+ .description('Run a small child process under the current dotenv (shell-off)')
232
+ .option('--print <key>', 'dotenv key to print', 'APP_SETTING')
233
+ .action(async (opts) => {
234
+ const key = typeof opts.print === 'string' && opts.print.length > 0
235
+ ? opts.print
236
+ : 'APP_SETTING';
237
+ // Build a minimal node -e payload via argv array (avoid quoting issues).
238
+ const code = `console.log(process.env.${key} ?? "")`;
239
+ const ctx = cli.getCtx();
240
+ const dotenv = (ctx?.dotenv ?? {});
241
+ // Inherit stdio for an interactive demo. Use --capture for CI.
242
+ await runCommand(['node', '-e', code], false, {
243
+ env: { ...process.env, ...dotenv },
244
+ stdio: 'inherit',
245
+ });
246
+ });
247
+ /**
248
+ * demo script [command...]
249
+ * Resolve and execute a command using the current scripts table and
250
+ * shell preference (with per-script overrides).
251
+ *
252
+ * How it works:
253
+ * - We read the merged CLI options persisted by the shipped CLI’s
254
+ * passOptions() hook on the current command instance’s parent.
255
+ * - resolveCommand resolves a script name → cmd or passes through a raw
256
+ * command string.
257
+ * - resolveShell chooses the appropriate shell:
258
+ * scripts[name].shell ?? global shell (string|boolean).
259
+ */
260
+ ns.command('script')
261
+ .description('Resolve a command via scripts and execute it with the proper shell')
262
+ .argument('[command...]')
263
+ .action(async (commandParts, _opts, thisCommand) => {
264
+ // Safely access the parent’s merged options (installed by passOptions()).
265
+ const parent = thisCommand.parent;
266
+ const bag = (parent?.getDotenvCliOptions ?? {});
267
+ const input = Array.isArray(commandParts)
268
+ ? commandParts.map(String).join(' ')
269
+ : '';
270
+ if (!input) {
271
+ logger.log('[demo] Please provide a command or script name, e.g. "echo OK" or "git-status".');
272
+ return;
273
+ }
274
+ const resolved = resolveCommand(bag?.scripts, input);
275
+ const shell = resolveShell(bag?.scripts, input, bag?.shell);
276
+ // Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
277
+ const ctx = cli.getCtx();
278
+ const dotenv = (ctx?.dotenv ?? {});
279
+ await runCommand(resolved, shell, {
280
+ env: { ...process.env, ...dotenv },
281
+ stdio: 'inherit',
282
+ });
283
+ });
284
+ },
285
+ /**
286
+ * Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
287
+ * For the demo we just log once to hint where such logic would live.
288
+ */
289
+ afterResolve(_cli, ctx) {
290
+ const keys = Object.keys(ctx.dotenv);
291
+ if (keys.length > 0) {
292
+ // Keep noise low; a single-line breadcrumb is sufficient for the demo.
293
+ console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
294
+ }
295
+ },
296
+ });
297
+
298
+ export { demoPlugin };