@kjanat/dreamcli 0.0.0 → 1.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.
Files changed (101) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/LICENSE +22 -0
  3. package/README.md +370 -0
  4. package/dist/adapter-B37d9oia.mjs +1 -0
  5. package/dist/adapter-CCSh5juX.cjs +1 -0
  6. package/dist/adapter-DIwO-q7K.d.mts +3447 -0
  7. package/dist/adapter-DQnxxLiE.d.cts +3447 -0
  8. package/dist/auto-5cjZaF9V.mjs +3 -0
  9. package/dist/auto-B0eSgoDw.cjs +3 -0
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.cts +920 -0
  12. package/dist/index.d.mts +920 -0
  13. package/dist/index.mjs +10 -0
  14. package/dist/runtime.cjs +1 -0
  15. package/dist/runtime.d.cts +253 -0
  16. package/dist/runtime.d.mts +253 -0
  17. package/dist/runtime.mjs +1 -0
  18. package/dist/testkit-CEDYPvhF.mjs +14 -0
  19. package/dist/testkit-ClIKijxC.cjs +14 -0
  20. package/dist/testkit.cjs +1 -0
  21. package/dist/testkit.d.cts +25 -0
  22. package/dist/testkit.d.mts +25 -0
  23. package/dist/testkit.mjs +1 -0
  24. package/examples/basic.ts +33 -0
  25. package/examples/gh/package.json +48 -0
  26. package/examples/gh/src/commands/auth.ts +66 -0
  27. package/examples/gh/src/commands/issue.ts +120 -0
  28. package/examples/gh/src/commands/pr.ts +125 -0
  29. package/examples/gh/src/data/issues.yaml +5 -0
  30. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  31. package/examples/gh/src/data/pull-requests.yaml +7 -0
  32. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  33. package/examples/gh/src/lib/auth.ts +37 -0
  34. package/examples/gh/src/lib/utils.ts +17 -0
  35. package/examples/gh/src/main.test.ts +306 -0
  36. package/examples/gh/src/main.ts +38 -0
  37. package/examples/gh/tsconfig.json +37 -0
  38. package/examples/interactive.ts +66 -0
  39. package/examples/json-mode.ts +93 -0
  40. package/examples/middleware.ts +71 -0
  41. package/examples/multi-command.ts +66 -0
  42. package/examples/spinner-progress.ts +49 -0
  43. package/examples/testing.ts +145 -0
  44. package/examples/tsconfig.json +17 -0
  45. package/package.json +123 -2
  46. package/src/core/cli/AGENTS.md +72 -0
  47. package/src/core/cli/dispatch.ts +282 -0
  48. package/src/core/cli/index.ts +1425 -0
  49. package/src/core/cli/plugin.ts +111 -0
  50. package/src/core/cli/propagate.ts +97 -0
  51. package/src/core/cli/root-help.ts +269 -0
  52. package/src/core/cli/root-surface.ts +74 -0
  53. package/src/core/completion/AGENTS.md +72 -0
  54. package/src/core/completion/completion-test-helpers.ts +48 -0
  55. package/src/core/completion/index.ts +82 -0
  56. package/src/core/completion/shells/bash.ts +456 -0
  57. package/src/core/completion/shells/fish.ts +24 -0
  58. package/src/core/completion/shells/powershell.ts +24 -0
  59. package/src/core/completion/shells/shared.ts +283 -0
  60. package/src/core/completion/shells/zsh.ts +376 -0
  61. package/src/core/config/index.ts +404 -0
  62. package/src/core/config/package-json.ts +216 -0
  63. package/src/core/errors/index.ts +178 -0
  64. package/src/core/help/index.ts +559 -0
  65. package/src/core/json-schema/index.ts +705 -0
  66. package/src/core/output/AGENTS.md +69 -0
  67. package/src/core/output/activity.ts +568 -0
  68. package/src/core/output/display-value.ts +48 -0
  69. package/src/core/output/index.ts +704 -0
  70. package/src/core/output/writer.ts +46 -0
  71. package/src/core/parse/index.ts +643 -0
  72. package/src/core/prompt/index.ts +566 -0
  73. package/src/core/resolve/AGENTS.md +69 -0
  74. package/src/core/resolve/index.ts +1331 -0
  75. package/src/core/schema/AGENTS.md +61 -0
  76. package/src/core/schema/activity.ts +237 -0
  77. package/src/core/schema/arg.ts +707 -0
  78. package/src/core/schema/command.ts +1263 -0
  79. package/src/core/schema/flag.ts +651 -0
  80. package/src/core/schema/index.ts +82 -0
  81. package/src/core/schema/middleware.ts +171 -0
  82. package/src/core/schema/prompt.ts +148 -0
  83. package/src/core/schema/run.ts +187 -0
  84. package/src/core/testkit/AGENTS.md +55 -0
  85. package/src/core/testkit/index.ts +365 -0
  86. package/src/index.ts +164 -0
  87. package/src/runtime/AGENTS.md +74 -0
  88. package/src/runtime/adapter.ts +300 -0
  89. package/src/runtime/auto.ts +110 -0
  90. package/src/runtime/bun.ts +55 -0
  91. package/src/runtime/deno.ts +355 -0
  92. package/src/runtime/detect.ts +102 -0
  93. package/src/runtime/index.ts +21 -0
  94. package/src/runtime/node-builtins.d.ts +23 -0
  95. package/src/runtime/node.ts +278 -0
  96. package/src/runtime/paths.ts +56 -0
  97. package/src/runtime/support.ts +119 -0
  98. package/src/runtime/test-helpers.ts +40 -0
  99. package/src/runtime.ts +31 -0
  100. package/src/testkit.ts +23 -0
  101. package/src/version.ts +20 -0
@@ -0,0 +1,1425 @@
1
+ /**
2
+ * CLI entry point builder with command registration and dispatch.
3
+ *
4
+ * The `cli()` factory returns an immutable `CLIBuilder` that registers
5
+ * commands, handles `--help`/`--version` at root level, dispatches to
6
+ * the matched command, and provides both a testable `.execute()` path
7
+ * and a production `.run()` path.
8
+ *
9
+ * @module dreamcli/core/cli
10
+ */
11
+
12
+ import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
+ import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
14
+ import type { FormatLoader } from '#internals/core/config/index.ts';
15
+ import { discoverConfig } from '#internals/core/config/index.ts';
16
+ import { discoverPackageJson, inferCliName } from '#internals/core/config/package-json.ts';
17
+ import { CLIError, ParseError } from '#internals/core/errors/index.ts';
18
+ import type { HelpOptions } from '#internals/core/help/index.ts';
19
+ import { formatHelp } from '#internals/core/help/index.ts';
20
+ import type { CapturedOutput, Verbosity } from '#internals/core/output/index.ts';
21
+ import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
22
+ import { parse } from '#internals/core/parse/index.ts';
23
+ import type { PromptEngine, TestAnswer } from '#internals/core/prompt/index.ts';
24
+ import { createTerminalPrompter } from '#internals/core/prompt/index.ts';
25
+ import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
26
+ import { arg } from '#internals/core/schema/arg.ts';
27
+ import type {
28
+ CommandBuilder,
29
+ CommandMeta,
30
+ CommandSchema,
31
+ ErasedCommand,
32
+ Out,
33
+ } from '#internals/core/schema/command.ts';
34
+ import { command } from '#internals/core/schema/command.ts';
35
+ import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
36
+ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
37
+ import { runCommand } from '#internals/core/testkit/index.ts';
38
+ import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
39
+ import { createAdapter } from '#internals/runtime/auto.ts';
40
+ import { dispatch, findClosestCommand } from './dispatch.ts';
41
+ import type { CLIPlugin } from './plugin.ts';
42
+ import { plugin } from './plugin.ts';
43
+ import { collectPropagatedFlags } from './propagate.ts';
44
+ import { formatRootHelp } from './root-help.ts';
45
+
46
+ // --- Type-erased command — erasure function (interface now in schema/command.ts)
47
+
48
+ /**
49
+ * Erase a typed CommandBuilder into an ErasedCommand, recursively
50
+ * building the subcommand tree.
51
+ *
52
+ * The closure captures the fully-typed builder, so `runCommand()` receives
53
+ * the original `CommandBuilder<F, A>` — no type assertions needed.
54
+ * Subcommands are recursively erased and indexed by name and alias for
55
+ * O(1) lookup during dispatch.
56
+ *
57
+ * @internal
58
+ */
59
+ function eraseCommand<
60
+ F extends Record<string, FlagBuilder<FlagConfig>>,
61
+ A extends Record<string, ArgBuilder<ArgConfig>>,
62
+ C extends Record<string, unknown>,
63
+ >(cmd: CommandBuilder<F, A, C>): ErasedCommand {
64
+ // Recursively erase subcommands, keyed by name and alias.
65
+ const subcommands = new Map<string, ErasedCommand>();
66
+ for (const sub of cmd._subcommands) {
67
+ const erased = eraseCommand(sub);
68
+ subcommands.set(sub.schema.name, erased);
69
+ for (const alias of sub.schema.aliases) {
70
+ subcommands.set(alias, erased);
71
+ }
72
+ }
73
+
74
+ return {
75
+ schema: cmd.schema,
76
+ subcommands,
77
+ _execute(argv, options) {
78
+ return runCommand(cmd, argv, options);
79
+ },
80
+ };
81
+ }
82
+
83
+ // --- CLI schema — runtime descriptor for the CLI program
84
+
85
+ /**
86
+ * Runtime descriptor for the CLI program.
87
+ *
88
+ * Stores the program name, version, description, and registered commands.
89
+ * Built incrementally by `CLIBuilder`.
90
+ */
91
+ interface CLISchema {
92
+ /** Program name (used in help text, usage lines, and completion scripts). */
93
+ readonly name: string;
94
+ /**
95
+ * Whether `.run()` should replace `name` with the invoked program name.
96
+ *
97
+ * Set via the `cli({ inherit: true })` factory form.
98
+ */
99
+ readonly inheritName: boolean;
100
+ /** Program version (shown by `--version`). */
101
+ readonly version: string | undefined;
102
+ /** Program description (shown in root help). */
103
+ readonly description: string | undefined;
104
+ /** Registered commands (type-erased for heterogeneous storage). */
105
+ readonly commands: readonly ErasedCommand[];
106
+ /**
107
+ * Default command dispatched when no subcommand matches.
108
+ *
109
+ * When set, the CLI root behaves like a hybrid command group: subcommands
110
+ * dispatch by name as usual, but empty argv or flags-only argv falls
111
+ * through to this command instead of showing root help.
112
+ *
113
+ * Set via the `.default()` builder method.
114
+ */
115
+ readonly defaultCommand: ErasedCommand | undefined;
116
+ /**
117
+ * Config discovery settings. When defined, `.run()` auto-discovers and
118
+ * loads a config file before command dispatch.
119
+ *
120
+ * Set via the `.config()` builder method.
121
+ */
122
+ readonly configSettings: ConfigSettings | undefined;
123
+ /**
124
+ * Package.json auto-discovery settings. When defined, `.run()` discovers
125
+ * the nearest `package.json` and merges metadata before dispatch.
126
+ *
127
+ * Set via the `.packageJson()` builder method.
128
+ */
129
+ readonly packageJsonSettings: PackageJsonSettings | undefined;
130
+ /** Registered CLI plugins. */
131
+ readonly plugins: readonly CLIPlugin[];
132
+ }
133
+
134
+ /**
135
+ * Config discovery settings for automatic config file loading.
136
+ *
137
+ * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
138
+ * call {@link discoverConfig} before dispatching to a command.
139
+ */
140
+ interface ConfigSettings {
141
+ /**
142
+ * Application name used to build config search paths.
143
+ *
144
+ * Search paths: `.{appName}.json` (cwd), `{appName}.config.json` (cwd),
145
+ * and `{configDir}/{appName}/config.json` where `configDir` is
146
+ * `$XDG_CONFIG_HOME` / `~/.config` on Unix or `%APPDATA%` /
147
+ * `%USERPROFILE%\\AppData\\Roaming` on Windows.
148
+ */
149
+ readonly appName: string;
150
+
151
+ /** Additional format loaders beyond the built-in JSON loader. */
152
+ readonly loaders: readonly FormatLoader[] | undefined;
153
+ }
154
+
155
+ /**
156
+ * Package.json auto-discovery settings.
157
+ *
158
+ * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
159
+ * call {@link discoverPackageJson} before dispatching to a command.
160
+ */
161
+ interface PackageJsonSettings {
162
+ /**
163
+ * Infer CLI name from package.json `bin` keys or `name` field.
164
+ *
165
+ * When `true`, the discovered name replaces the `cli(name)` value.
166
+ * Explicit `.version()`/`.description()` calls still take precedence
167
+ * over discovered values.
168
+ *
169
+ * @defaultValue `false`
170
+ */
171
+ readonly inferName: boolean;
172
+ }
173
+
174
+ // --- Options for execute/run
175
+
176
+ /**
177
+ * Options for `CLIBuilder.execute()` and `CLIBuilder.run()`.
178
+ *
179
+ * Mirrors `RunOptions` from testkit but adds CLI-level concerns
180
+ * (version display, root help formatting, runtime adapter).
181
+ */
182
+ interface CLIRunOptions {
183
+ /**
184
+ * CLI plugins to apply for this execution.
185
+ *
186
+ * @internal — populated from `CLIBuilder.schema.plugins` during dispatch.
187
+ */
188
+ readonly plugins?: readonly CLIPlugin[];
189
+
190
+ /**
191
+ * Runtime adapter providing platform-specific I/O, argv, env, etc.
192
+ *
193
+ * When provided to `.run()`, replaces the default Node adapter.
194
+ * Ignored by `.execute()` (which is process-free by design).
195
+ */
196
+ readonly adapter?: RuntimeAdapter;
197
+
198
+ /**
199
+ * Environment variables for flag resolution.
200
+ *
201
+ * Flags with `.env('VAR')` configured resolve from this record
202
+ * when no CLI value is provided (CLI → env → config → default).
203
+ */
204
+ readonly env?: Readonly<Record<string, string | undefined>>;
205
+
206
+ /**
207
+ * Configuration object for flag resolution.
208
+ *
209
+ * Flags with `.config('path')` configured resolve from this record
210
+ * when no CLI or env value is provided (CLI → env → config → prompt → default).
211
+ * Config is plain JSON — file loading is the caller's responsibility.
212
+ */
213
+ readonly config?: Readonly<Record<string, unknown>>;
214
+
215
+ /**
216
+ * Full stdin contents for args configured with `.stdin()`.
217
+ *
218
+ * `run()` populates this from `adapter.readStdin()` only when the selected
219
+ * invocation needs stdin. `execute()` accepts it directly so tests can
220
+ * simulate piped input without a runtime adapter.
221
+ */
222
+ readonly stdinData?: string | null;
223
+
224
+ /**
225
+ * Prompt engine for interactive flag resolution.
226
+ *
227
+ * When provided, flags with `.prompt()` configured that have no value
228
+ * after CLI/env/config resolution will be prompted interactively.
229
+ * When absent (and `answers` is also absent), prompting is skipped.
230
+ *
231
+ * Takes precedence over `answers` when both are provided.
232
+ */
233
+ readonly prompter?: PromptEngine;
234
+
235
+ /**
236
+ * Pre-configured prompt answers for testing convenience.
237
+ *
238
+ * When provided, a test prompter is created from these answers via
239
+ * `createTestPrompter(answers)`. Each entry is consumed in order —
240
+ * use `PROMPT_CANCEL` to simulate cancellation.
241
+ *
242
+ * Ignored when an explicit `prompter` is provided.
243
+ */
244
+ readonly answers?: readonly TestAnswer[];
245
+
246
+ /**
247
+ * Verbosity level for the output channel.
248
+ * @defaultValue `'normal'`
249
+ */
250
+ readonly verbosity?: Verbosity;
251
+
252
+ /**
253
+ * Enable JSON output mode.
254
+ *
255
+ * When `true`, `log` and `info` messages are redirected to stderr
256
+ * so that stdout is reserved exclusively for structured `json()` output.
257
+ * Errors are also rendered as JSON to stderr.
258
+ *
259
+ * @defaultValue `false`
260
+ */
261
+ readonly jsonMode?: boolean;
262
+
263
+ /**
264
+ * Whether stdout is connected to a TTY.
265
+ *
266
+ * When provided, propagated to the output channel's `isTTY` field.
267
+ * In `.run()`, automatically sourced from `adapter.isTTY` when not
268
+ * explicitly set.
269
+ *
270
+ * @defaultValue `false`
271
+ */
272
+ readonly isTTY?: boolean;
273
+
274
+ /**
275
+ * Output channel override used by `run()` for live terminal rendering.
276
+ *
277
+ * @internal — `execute()` remains capture-first by default.
278
+ */
279
+ readonly out?: Out;
280
+
281
+ /**
282
+ * Capture buffers paired with `out`.
283
+ *
284
+ * @internal — `run()` omits this and accepts empty buffers in the returned
285
+ * `RunResult` because output is already written to the real adapter streams.
286
+ */
287
+ readonly captured?: CapturedOutput;
288
+
289
+ /**
290
+ * Help formatting options (width, binName).
291
+ * `binName` defaults to the CLI program name.
292
+ */
293
+ readonly help?: HelpOptions;
294
+ }
295
+
296
+ // --- --config flag extraction
297
+
298
+ /**
299
+ * Extract `--config <path>` or `--config=<path>` from argv.
300
+ *
301
+ * Returns the config path (if present) and the filtered argv with the
302
+ * flag (and its value) removed. Bare `--config` at end of argv (no value)
303
+ * and `--config=` (empty value) are silently ignored (treated as absent).
304
+ *
305
+ * The `--config=<path>` form is checked first so that a bare `--config`
306
+ * token does not consume the next element when an equals-form is present.
307
+ *
308
+ * @param argv - Raw argument vector to scan for `--config`.
309
+ * @returns The extracted config path and filtered argv with the flag removed.
310
+ *
311
+ * @internal
312
+ */
313
+ function extractConfigFlag(argv: readonly string[]): {
314
+ readonly configPath: string | undefined;
315
+ readonly filteredArgv: readonly string[];
316
+ } {
317
+ // --- equals form: --config=<path> ---
318
+ const eqIdx = argv.findIndex((arg) => arg.startsWith('--config='));
319
+ if (eqIdx !== -1) {
320
+ const value = (argv[eqIdx] as string).slice('--config='.length);
321
+ // Always strip the element; empty value (--config=) treated as absent.
322
+ const filteredArgv = [...argv.slice(0, eqIdx), ...argv.slice(eqIdx + 1)];
323
+ return {
324
+ configPath: value.length > 0 ? value : undefined,
325
+ filteredArgv,
326
+ };
327
+ }
328
+
329
+ // --- space-separated form: --config <path> ---
330
+ const idx = argv.indexOf('--config');
331
+ const nextArg = idx >= 0 ? argv[idx + 1] : undefined;
332
+ if (idx === -1 || nextArg === undefined) {
333
+ return { configPath: undefined, filteredArgv: argv };
334
+ }
335
+ const filteredArgv = [...argv.slice(0, idx), ...argv.slice(idx + 2)];
336
+ return { configPath: nextArg, filteredArgv };
337
+ }
338
+
339
+ // --- CLI → CommandMeta builder
340
+
341
+ /**
342
+ * Build {@link CommandMeta} from CLI-level schema and the leaf command name.
343
+ *
344
+ * @param cliSchema - Root CLI schema providing program name and version.
345
+ * @param helpOptions - Help formatting options; `binName` overrides the program name when set.
346
+ * @param commandName - Name of the matched leaf command.
347
+ * @returns Metadata record consumed by command actions and help formatters.
348
+ *
349
+ * @internal
350
+ */
351
+ function buildMeta(
352
+ cliSchema: CLISchema,
353
+ helpOptions: HelpOptions,
354
+ commandName: string,
355
+ ): CommandMeta {
356
+ return {
357
+ name: cliSchema.name,
358
+ bin: helpOptions.binName ?? cliSchema.name,
359
+ version: cliSchema.version,
360
+ command: commandName,
361
+ };
362
+ }
363
+
364
+ // --- Command run options builder
365
+
366
+ /**
367
+ * Build `RunOptions` from `CLIRunOptions`, conditionally spreading each
368
+ * field to satisfy `exactOptionalPropertyTypes`.
369
+ *
370
+ * @param options - CLI-level run options (may be `undefined` for defaults).
371
+ * @param helpOptions - Help formatting options forwarded to commands.
372
+ * @param meta - Optional command metadata (omitted for root-level dispatch).
373
+ * @returns Options record ready for `ErasedCommand._execute()`.
374
+ *
375
+ * @internal
376
+ */
377
+ function buildCommandRunOptions(
378
+ options: CLIRunOptions | undefined,
379
+ helpOptions: HelpOptions,
380
+ meta?: CommandMeta,
381
+ ): RunOptions {
382
+ return {
383
+ help: helpOptions,
384
+ ...(meta !== undefined ? { meta } : {}),
385
+ ...(options?.plugins !== undefined ? { plugins: options.plugins } : {}),
386
+ ...(options?.env !== undefined ? { env: options.env } : {}),
387
+ ...(options?.config !== undefined ? { config: options.config } : {}),
388
+ ...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
389
+ ...(options?.prompter !== undefined ? { prompter: options.prompter } : {}),
390
+ ...(options?.answers !== undefined ? { answers: options.answers } : {}),
391
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
392
+ ...(options?.jsonMode !== undefined ? { jsonMode: options.jsonMode } : {}),
393
+ ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
394
+ ...(options?.out !== undefined ? { out: options.out } : {}),
395
+ ...(options?.captured !== undefined ? { captured: options.captured } : {}),
396
+ };
397
+ }
398
+
399
+ /**
400
+ * Index commands by name and alias for O(1) dispatch lookup.
401
+ *
402
+ * @param commands - Registered top-level commands.
403
+ * @returns Map keyed by command name and every alias.
404
+ *
405
+ * @internal
406
+ */
407
+ function buildRootCommandMap(
408
+ commands: readonly ErasedCommand[],
409
+ ): ReadonlyMap<string, ErasedCommand> {
410
+ const rootCommands = new Map<string, ErasedCommand>();
411
+ for (const cmd of commands) {
412
+ rootCommands.set(cmd.schema.name, cmd);
413
+ for (const alias of cmd.schema.aliases) {
414
+ rootCommands.set(alias, cmd);
415
+ }
416
+ }
417
+ return rootCommands;
418
+ }
419
+
420
+ /**
421
+ * Check whether a single command's args require stdin for the given argv.
422
+ *
423
+ * @param schema - Command schema whose args are inspected for `.stdin()` configuration.
424
+ * @param argv - Remaining argv tokens after dispatch (excludes the command name).
425
+ * @returns `true` when at least one arg has `stdinMode` and its parsed value is absent or `'-'`.
426
+ *
427
+ * @internal
428
+ */
429
+ function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean {
430
+ if (argv.includes('--help') || argv.includes('-h')) {
431
+ return false;
432
+ }
433
+
434
+ try {
435
+ const parsed = parse(schema, argv);
436
+ return schema.args.some(({ name, schema: argSchema }) => {
437
+ const parsedValue = parsed.args[name];
438
+ return argSchema.stdinMode && (parsedValue === undefined || parsedValue === '-');
439
+ });
440
+ } catch (err: unknown) {
441
+ if (err instanceof ParseError) {
442
+ return false;
443
+ }
444
+ throw err;
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Determine whether the full CLI invocation will need stdin data.
450
+ *
451
+ * Dispatches argv through the command tree to find the target command,
452
+ * then delegates to {@link commandInvocationNeedsStdin}. Short-circuits
453
+ * to `false` for `--help`, `--version`, virtual `help`, and empty argv
454
+ * without a default command.
455
+ *
456
+ * @param builder - CLI builder whose schema and command tree are inspected.
457
+ * @param argv - Raw argv tokens (after `--json` stripping).
458
+ * @returns `true` when the resolved command has args that require stdin.
459
+ *
460
+ * @internal
461
+ */
462
+ function invocationNeedsStdin(builder: CLIBuilder, argv: readonly string[]): boolean {
463
+ const filteredArgv = argv.includes('--json') ? argv.filter((arg) => arg !== '--json') : argv;
464
+
465
+ if (filteredArgv.includes('--version') || filteredArgv.includes('-V')) {
466
+ return false;
467
+ }
468
+ if (filteredArgv.includes('--help') || filteredArgv.includes('-h')) {
469
+ return false;
470
+ }
471
+
472
+ const firstArg = filteredArgv[0];
473
+ if (firstArg === 'help') {
474
+ const hasRealHelpCommand = builder.schema.commands.some(
475
+ (command) => command.schema.name === 'help' || command.schema.aliases.includes('help'),
476
+ );
477
+ if (!hasRealHelpCommand) {
478
+ return false;
479
+ }
480
+ }
481
+
482
+ if (firstArg === undefined && builder.schema.defaultCommand === undefined) {
483
+ return false;
484
+ }
485
+ if (builder.schema.commands.length === 0) {
486
+ return false;
487
+ }
488
+
489
+ const rootCommands = buildRootCommandMap(builder.schema.commands);
490
+ const result = dispatch(filteredArgv, rootCommands);
491
+ const defaultCommand = builder.schema.defaultCommand;
492
+
493
+ switch (result.kind) {
494
+ case 'unknown': {
495
+ if (defaultCommand !== undefined && result.parentPath.length === 0) {
496
+ const suggestion =
497
+ result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
498
+ if (suggestion === undefined) {
499
+ return commandInvocationNeedsStdin(defaultCommand.schema, filteredArgv);
500
+ }
501
+ }
502
+ return false;
503
+ }
504
+
505
+ case 'needs-subcommand':
506
+ return false;
507
+
508
+ case 'match': {
509
+ const propagated = collectPropagatedFlags(result.commandPath);
510
+ const mergedSchema =
511
+ Object.keys(propagated).length > 0
512
+ ? {
513
+ ...result.command.schema,
514
+ flags: { ...propagated, ...result.command.schema.flags },
515
+ }
516
+ : result.command.schema;
517
+ return commandInvocationNeedsStdin(mergedSchema, result.remainingArgv);
518
+ }
519
+ }
520
+ }
521
+
522
+ // --- CLIBuilder — immutable builder for the CLI program
523
+
524
+ /**
525
+ * Immutable CLI program builder.
526
+ *
527
+ * Registers commands, handles root-level `--help`/`--version`, and
528
+ * dispatches to the matched command based on argv.
529
+ *
530
+ * Two execution paths:
531
+ * - `.execute(argv, options?)` — testable, returns `RunResult`
532
+ * - `.run(options?)` — production entry, reads `process.argv`, exits process
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * import { cli, command, flag, arg } from 'dreamcli';
537
+ *
538
+ * const deploy = command('deploy')
539
+ * .arg('target', arg.string())
540
+ * .flag('force', flag.boolean().alias('f'))
541
+ * .action(({ args, flags, out }) => {
542
+ * out.log(`Deploying ${args.target}...`);
543
+ * });
544
+ *
545
+ * cli('mycli')
546
+ * .version('1.0.0')
547
+ * .command(deploy)
548
+ * .run();
549
+ * ```
550
+ */
551
+ class CLIBuilder {
552
+ /** @internal Runtime schema descriptor. */
553
+ readonly schema: CLISchema;
554
+
555
+ constructor(schema: CLISchema) {
556
+ this.schema = schema;
557
+ }
558
+
559
+ // -- Metadata modifiers --------------------------------------------------
560
+
561
+ /**
562
+ * Set the program version (shown by `--version`).
563
+ *
564
+ * @param v - Semantic version string.
565
+ * @returns The builder (for chaining).
566
+ */
567
+ version(v: string): CLIBuilder {
568
+ return new CLIBuilder({ ...this.schema, version: v });
569
+ }
570
+
571
+ /**
572
+ * Set the program description (shown in root help).
573
+ *
574
+ * @param text - Short description displayed in root help output.
575
+ * @returns The builder (for chaining).
576
+ */
577
+ description(text: string): CLIBuilder {
578
+ return new CLIBuilder({ ...this.schema, description: text });
579
+ }
580
+
581
+ /**
582
+ * Enable automatic config file discovery.
583
+ *
584
+ * When enabled, `.run()` probes standard paths before dispatching:
585
+ * 1. `$CWD/.{appName}.json`
586
+ * 2. `$CWD/{appName}.config.json`
587
+ * 3. `$CONFIG_DIR/{appName}/config.json`
588
+ * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
589
+ * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
590
+ *
591
+ * The user can override the path via `--config <path>` or `--config=<path>`.
592
+ *
593
+ * Loaded config feeds into the resolution chain
594
+ * (CLI → env → **config** → prompt → default) for flags that
595
+ * declare `.config('dotted.path')`.
596
+ *
597
+ * Has no effect in `.execute()` (which receives config via
598
+ * `options.config` directly).
599
+ *
600
+ * @param appName - Name used to build search paths.
601
+ * @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
602
+ * @returns The builder (for chaining).
603
+ */
604
+ config(appName: string, loaders?: readonly FormatLoader[]): CLIBuilder {
605
+ return new CLIBuilder({
606
+ ...this.schema,
607
+ configSettings: {
608
+ appName,
609
+ loaders,
610
+ },
611
+ });
612
+ }
613
+
614
+ /**
615
+ * Register a custom config format loader.
616
+ *
617
+ * Adds a {@link FormatLoader} incrementally — call multiple times to
618
+ * register multiple formats. Loaders registered later for the same
619
+ * extension override earlier ones.
620
+ *
621
+ * Requires `.config()` to have been called first (sets the app name).
622
+ *
623
+ * @param loader - Format loader (or extensions + parse function).
624
+ * @returns The builder (for chaining).
625
+ *
626
+ * @example Bun built-in parsers
627
+ * ```ts
628
+ * import { configFormat } from 'dreamcli';
629
+ *
630
+ * cli('myapp')
631
+ * .config('myapp')
632
+ * .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
633
+ * .configLoader(configFormat(['toml'], Bun.TOML.parse))
634
+ * .run();
635
+ * ```
636
+ *
637
+ * @example npm package parsers
638
+ * ```ts
639
+ * import { configFormat } from 'dreamcli';
640
+ * import { parse as parseYaml } from 'yaml';
641
+ * import { parse as parseTOML } from '@iarna/toml';
642
+ *
643
+ * cli('myapp')
644
+ * .config('myapp')
645
+ * .configLoader(configFormat(['yaml', 'yml'], parseYaml))
646
+ * .configLoader(configFormat(['toml'], parseTOML))
647
+ * .run();
648
+ * ```
649
+ */
650
+ configLoader(loader: FormatLoader): CLIBuilder {
651
+ if (this.schema.configSettings === undefined) {
652
+ throw new CLIError('.configLoader() requires .config() to be called first', {
653
+ code: 'INVALID_BUILDER_STATE',
654
+ suggest: 'Call .config(appName) before .configLoader()',
655
+ });
656
+ }
657
+ const existing = this.schema.configSettings.loaders ?? [];
658
+ return new CLIBuilder({
659
+ ...this.schema,
660
+ configSettings: {
661
+ ...this.schema.configSettings,
662
+ loaders: [...existing, loader],
663
+ },
664
+ });
665
+ }
666
+
667
+ /**
668
+ * Enable automatic package.json metadata discovery.
669
+ *
670
+ * When enabled, `.run()` walks up from `cwd` to find the nearest
671
+ * `package.json` and merges its `version` and `description` fields
672
+ * into the CLI schema. Explicit `.version()` and `.description()`
673
+ * calls always take precedence over discovered values.
674
+ *
675
+ * Has no effect in `.execute()` (which is filesystem-free by design).
676
+ *
677
+ * @param settings - Optional settings. Pass `{ inferName: true }` to
678
+ * also infer the CLI name from `bin` keys or the package `name` field.
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * // Auto-fill version + description from nearest package.json:
683
+ * cli('mycli')
684
+ * .packageJson()
685
+ * .command(deploy)
686
+ * .run();
687
+ *
688
+ * // Also infer CLI name from bin key / package name:
689
+ * cli('mycli')
690
+ * .packageJson({ inferName: true })
691
+ * .command(deploy)
692
+ * .run();
693
+ *
694
+ * // Explicit values always win:
695
+ * cli('mycli')
696
+ * .packageJson()
697
+ * .version('2.0.0-beta') // wins over package.json
698
+ * .run();
699
+ * ```
700
+ */
701
+ packageJson(settings?: { readonly inferName?: boolean }): CLIBuilder {
702
+ return new CLIBuilder({
703
+ ...this.schema,
704
+ packageJsonSettings: {
705
+ inferName: settings?.inferName ?? false,
706
+ },
707
+ });
708
+ }
709
+
710
+ // -- Command registration ------------------------------------------------
711
+
712
+ /**
713
+ * Register a command with the CLI program.
714
+ *
715
+ * The command's type parameters are erased for heterogeneous storage.
716
+ * Type safety is preserved inside the closure that delegates to
717
+ * `runCommand()`.
718
+ *
719
+ * @param cmd - {@link CommandBuilder} to register.
720
+ * @returns The builder (for chaining).
721
+ */
722
+ command<
723
+ F extends Record<string, FlagBuilder<FlagConfig>>,
724
+ A extends Record<string, ArgBuilder<ArgConfig>>,
725
+ C extends Record<string, unknown>,
726
+ >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
727
+ return new CLIBuilder({
728
+ ...this.schema,
729
+ commands: [...this.schema.commands, eraseCommand(cmd)],
730
+ });
731
+ }
732
+
733
+ /**
734
+ * Register a command as the default — dispatched when no subcommand is given.
735
+ *
736
+ * The CLI root behaves like a hybrid command group: named subcommands
737
+ * dispatch normally, but empty argv or flags-only argv falls through to
738
+ * this command instead of showing root help.
739
+ *
740
+ * The command is also registered as a normal subcommand (can be invoked
741
+ * by name). Only one default command is allowed.
742
+ *
743
+ * @example
744
+ * ```ts
745
+ * // Single-command CLI — no subcommand name needed:
746
+ * // mytool --force production
747
+ * cli('mytool')
748
+ * .default(deploy)
749
+ * .run();
750
+ *
751
+ * // Multi-command CLI with a default:
752
+ * // mytool production → runs deploy
753
+ * // mytool status → runs status
754
+ * cli('mytool')
755
+ * .default(deploy)
756
+ * .command(status)
757
+ * .run();
758
+ * ```
759
+ *
760
+ * @param cmd - {@link CommandBuilder} to register as the default.
761
+ * @returns The builder (for chaining).
762
+ */
763
+ default<
764
+ F extends Record<string, FlagBuilder<FlagConfig>>,
765
+ A extends Record<string, ArgBuilder<ArgConfig>>,
766
+ C extends Record<string, unknown>,
767
+ >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
768
+ if (this.schema.defaultCommand !== undefined) {
769
+ throw new CLIError('Only one default command is allowed', {
770
+ code: 'DUPLICATE_DEFAULT',
771
+ suggest: 'Call .default() only once when building the CLI',
772
+ });
773
+ }
774
+ if (this.schema.commands.some((c) => c.schema.name === cmd.schema.name)) {
775
+ throw new CLIError(`Command '${cmd.schema.name}' is already registered`, {
776
+ code: 'DUPLICATE_COMMAND',
777
+ suggest: 'Use .default() instead of .command() to register the default command',
778
+ });
779
+ }
780
+ const erased = eraseCommand(cmd);
781
+ return new CLIBuilder({
782
+ ...this.schema,
783
+ commands: [...this.schema.commands, erased],
784
+ defaultCommand: erased,
785
+ });
786
+ }
787
+
788
+ /**
789
+ * Register a CLI plugin.
790
+ *
791
+ * Plugins run in registration order. At each lifecycle stage, all hooks for
792
+ * the first plugin run before hooks for the second plugin, and so on.
793
+ *
794
+ * @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
795
+ * @returns The builder (for chaining).
796
+ * @see {@link plugin} to construct plugin definitions.
797
+ */
798
+ plugin(definition: CLIPlugin): CLIBuilder {
799
+ return new CLIBuilder({
800
+ ...this.schema,
801
+ plugins: [...this.schema.plugins, definition],
802
+ });
803
+ }
804
+
805
+ // -- Built-in subcommands ------------------------------------------------
806
+
807
+ /**
808
+ * Register a built-in `completions` subcommand that generates shell
809
+ * completion scripts.
810
+ *
811
+ * The generated command accepts a `--shell` flag (required, enum of
812
+ * all {@link Shell} values) and writes the completion script to stdout
813
+ * via `out.log()`. Unsupported shells throw a descriptive `CLIError`
814
+ * instead of a generic parse error.
815
+ *
816
+ * Call this **after** registering all other commands so the completion
817
+ * script includes the full command set. The captured schema is a
818
+ * snapshot at call time — commands registered after `.completions()`
819
+ * will not appear in the generated script. Completion options are also
820
+ * captured at call time.
821
+ *
822
+ * @example
823
+ * ```ts
824
+ * cli('mycli')
825
+ * .version('1.0.0')
826
+ * .command(deploy)
827
+ * .command(login)
828
+ * .completions({ rootMode: 'surface' })
829
+ * .run();
830
+ * ```
831
+ */
832
+ completions(options?: CompletionOptions): CLIBuilder {
833
+ if (this.schema.commands.some((c) => c.schema.name === 'completions')) {
834
+ throw new CLIError('.completions() has already been called', {
835
+ code: 'DUPLICATE_COMMAND',
836
+ suggest: 'Call .completions() only once when building the CLI',
837
+ });
838
+ }
839
+
840
+ // Capture current schema — includes all commands registered so far.
841
+ // The completions command itself is deliberately excluded from the
842
+ // generated script (it would be noise in shell completions).
843
+ const cliSchema = this.schema;
844
+ const completionOptions = options;
845
+
846
+ // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
847
+ const shellMap = new Map<string, Shell>();
848
+ for (const s of SHELLS) shellMap.set(s, s);
849
+
850
+ const cmd = command('completions')
851
+ .alias('completion')
852
+ .description('Generate shell completion script')
853
+ .arg(
854
+ 'shell',
855
+ arg
856
+ .custom((raw: string): Shell => {
857
+ // Normalize $SHELL paths across Unix/Windows:
858
+ // /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
859
+ const segments = raw.split(/[\\/]/);
860
+ const basename = segments[segments.length - 1] ?? raw;
861
+ const name = basename.replace(/\.(?:exe|cmd|bat)$/i, '');
862
+ const shell = shellMap.get(name);
863
+ if (shell === undefined) {
864
+ throw new Error(`Unknown shell '${name}'. Valid shells: ${SHELLS.join(', ')}`);
865
+ }
866
+ return shell;
867
+ })
868
+ .env('SHELL')
869
+ .describe(`Target shell (${SHELLS.join(', ')})`),
870
+ )
871
+ .action(({ args, meta, out }) => {
872
+ const completionSchema =
873
+ meta.bin === cliSchema.name ? cliSchema : { ...cliSchema, name: meta.bin };
874
+ const script = generateCompletion(completionSchema, args.shell, completionOptions);
875
+ if (out.jsonMode) {
876
+ out.json({ shell: args.shell, script });
877
+ } else {
878
+ out.log(script);
879
+ }
880
+ });
881
+ return this.command(cmd);
882
+ }
883
+
884
+ // -- Execution -----------------------------------------------------------
885
+
886
+ /**
887
+ * Execute the CLI program against explicit argv.
888
+ *
889
+ * This is the testable execution path — no process state is touched.
890
+ * Returns a structured `RunResult` with exit code and captured output.
891
+ *
892
+ * @param argv - Raw argv tokens (NOT including the binary/script path,
893
+ * i.e. equivalent to `process.argv.slice(2)`).
894
+ * @param options - Injectable runtime state.
895
+ * @returns Structured result with exit code and captured output.
896
+ */
897
+ async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
898
+ // -- Detect --json flag (global, extracted before command dispatch) ------
899
+ const hasJsonFlag = argv.includes('--json');
900
+ const jsonMode = hasJsonFlag || options?.jsonMode === true;
901
+ // Strip --json from argv so commands don't see it as an unknown flag
902
+ const filteredArgv = hasJsonFlag ? argv.filter((a) => a !== '--json') : argv;
903
+
904
+ const captureOptions = {
905
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
906
+ ...(jsonMode ? { jsonMode } : {}),
907
+ ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
908
+ };
909
+ let out: Out;
910
+ let captured: CapturedOutput;
911
+ if (options?.out !== undefined) {
912
+ out = options.out;
913
+ captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
914
+ } else {
915
+ [out, captured] = createCaptureOutput(
916
+ Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
917
+ );
918
+ }
919
+
920
+ // Resolve help options — default binName to CLI program name
921
+ const helpOptions: HelpOptions = {
922
+ ...options?.help,
923
+ binName: options?.help?.binName ?? this.schema.name,
924
+ };
925
+
926
+ // -- Root --version -------------------------------------------------------
927
+ if (
928
+ this.schema.version !== undefined &&
929
+ (filteredArgv.includes('--version') || filteredArgv.includes('-V'))
930
+ ) {
931
+ out.log(this.schema.version);
932
+ return buildResult(0, captured, undefined);
933
+ }
934
+
935
+ // -- Extract first arg for root-level checks --------------------------------
936
+ const firstArg = filteredArgv.length > 0 ? filteredArgv[0] : undefined;
937
+
938
+ // -- Root --help (explicit root-level help request) -----------------------
939
+ // Only intercept when --help/-h is the first token — subcommand-level
940
+ // help (e.g. `myapp deploy --help`) flows through dispatch.
941
+ if (firstArg === '--help' || firstArg === '-h') {
942
+ const helpText = formatRootHelp(this.schema, helpOptions);
943
+ out.log(helpText);
944
+ return buildResult(0, captured, undefined);
945
+ }
946
+
947
+ // -- `help [command...]` virtual subcommand ------------------------------
948
+ // Rewrite `help <cmd>` → `<cmd> --help` so it flows through normal
949
+ // dispatch and per-command help rendering. Bare `help` → root help.
950
+ // Only activates when the user hasn't registered a real `help` command.
951
+ if (firstArg === 'help') {
952
+ const hasRealHelpCommand = this.schema.commands.some(
953
+ (c) => c.schema.name === 'help' || c.schema.aliases.includes('help'),
954
+ );
955
+ if (!hasRealHelpCommand) {
956
+ const rest = filteredArgv.slice(1);
957
+ if (rest.length === 0) {
958
+ const helpText = formatRootHelp(this.schema, helpOptions);
959
+ out.log(helpText);
960
+ return buildResult(0, captured, undefined);
961
+ }
962
+ // Recurse with rewritten argv: `help deploy --force` → `deploy --force --help`
963
+ // Propagate jsonMode — `--json` was already stripped from filteredArgv above.
964
+ return this.execute([...rest, '--help'], jsonMode ? { ...options, jsonMode } : options);
965
+ }
966
+ }
967
+
968
+ // -- Empty argv without a default command → root help ---------------------
969
+ if (firstArg === undefined && this.schema.defaultCommand === undefined) {
970
+ const helpText = formatRootHelp(this.schema, helpOptions);
971
+ out.log(helpText);
972
+ return buildResult(0, captured, undefined);
973
+ }
974
+
975
+ // -- No commands registered -----------------------------------------------
976
+ if (this.schema.commands.length === 0) {
977
+ const err = new CLIError('No commands registered', {
978
+ code: 'NO_ACTION',
979
+ suggest: 'Add commands via .command() before calling .run()',
980
+ });
981
+ if (jsonMode) {
982
+ out.json({ error: err.toJSON() });
983
+ } else {
984
+ out.error(err.message);
985
+ }
986
+ return buildResult(1, captured, err);
987
+ }
988
+
989
+ // -- Build root command map for dispatch -----------------------------------
990
+ const rootCommands = buildRootCommandMap(this.schema.commands);
991
+
992
+ // -- Recursive dispatch ---------------------------------------------------
993
+ const result = dispatch(filteredArgv, rootCommands);
994
+
995
+ // -- Resolve default command (if configured) ------------------------------
996
+ const defaultCmd = this.schema.defaultCommand;
997
+
998
+ // -- Shared options for command execution ----------------------------------
999
+ const effectiveOptions: CLIRunOptions = {
1000
+ ...options,
1001
+ plugins: this.schema.plugins,
1002
+ ...(jsonMode ? { jsonMode } : {}),
1003
+ };
1004
+
1005
+ switch (result.kind) {
1006
+ case 'unknown': {
1007
+ if (defaultCmd !== undefined && result.parentPath.length === 0) {
1008
+ // Only delegate to the default command for root-level unknowns.
1009
+ // Nested unknowns (parentPath non-empty) should surface an error
1010
+ // so typo suggestions work correctly within command groups.
1011
+ const suggestion =
1012
+ result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
1013
+ if (suggestion === undefined) {
1014
+ const meta = buildMeta(this.schema, helpOptions, defaultCmd.schema.name);
1015
+ const commandRunOptions = buildCommandRunOptions(effectiveOptions, helpOptions, meta);
1016
+ return defaultCmd._execute(filteredArgv, { ...commandRunOptions });
1017
+ }
1018
+ }
1019
+
1020
+ if (result.input === '') {
1021
+ // Only flags, no command, no default.
1022
+ // Extract the first flag token to report it as unknown.
1023
+ const unknownFlag = filteredArgv.find((t) => t.startsWith('-'));
1024
+ if (unknownFlag !== undefined) {
1025
+ const err = new ParseError(`Unknown flag ${unknownFlag}`, {
1026
+ code: 'UNKNOWN_FLAG',
1027
+ suggest: `Run '${this.schema.name} --help' for available commands`,
1028
+ });
1029
+ if (jsonMode) {
1030
+ out.json({ error: err.toJSON() });
1031
+ } else {
1032
+ out.error(err.message);
1033
+ out.error(`Suggestion: ${err.suggest}`);
1034
+ }
1035
+ return buildResult(2, captured, err);
1036
+ }
1037
+ // Truly empty (shouldn't reach here — handled above) — show help.
1038
+ const helpText = formatRootHelp(this.schema, helpOptions);
1039
+ out.log(helpText);
1040
+ return buildResult(0, captured, undefined);
1041
+ }
1042
+ const suggestion = findClosestCommand(result.input, result.candidates);
1043
+
1044
+ // Build scoped help path from ancestor context.
1045
+ // e.g. for `myapp db migrat` → parentPath = [dbSchema] → "myapp db --help"
1046
+ const scopePath =
1047
+ result.parentPath.length > 0
1048
+ ? `${this.schema.name} ${result.parentPath.map((s) => s.name).join(' ')}`
1049
+ : this.schema.name;
1050
+
1051
+ const err = new ParseError(`Unknown command: ${result.input}`, {
1052
+ code: 'UNKNOWN_COMMAND',
1053
+ suggest:
1054
+ suggestion !== undefined
1055
+ ? `Did you mean '${suggestion}'?`
1056
+ : `Run '${scopePath} --help' for available commands`,
1057
+ });
1058
+ if (jsonMode) {
1059
+ out.json({ error: err.toJSON() });
1060
+ } else {
1061
+ out.error(err.message);
1062
+ if (err.suggest !== undefined) {
1063
+ out.error(`Suggestion: ${err.suggest}`);
1064
+ }
1065
+ }
1066
+ return buildResult(2, captured, err);
1067
+ }
1068
+
1069
+ case 'needs-subcommand': {
1070
+ // Group command with no handler — show its help via formatHelp().
1071
+ // Build binName from full command path so usage reads "myapp db" not just "db".
1072
+ const ancestorNames = result.commandPath.slice(0, -1).map((s) => s.name);
1073
+ const groupBinName = [this.schema.name, ...ancestorNames].join(' ');
1074
+ const groupHelpOptions: HelpOptions = {
1075
+ ...helpOptions,
1076
+ binName: groupBinName,
1077
+ };
1078
+ const helpText = formatHelp(result.command.schema, groupHelpOptions);
1079
+ out.log(helpText);
1080
+ return buildResult(0, captured, undefined);
1081
+ }
1082
+
1083
+ case 'match': {
1084
+ // Merge propagated flags from ancestor path into target's schema.
1085
+ const propagated = collectPropagatedFlags(result.commandPath);
1086
+ const hasPropagated = Object.keys(propagated).length > 0;
1087
+ const mergedSchema: CommandSchema | undefined = hasPropagated
1088
+ ? {
1089
+ ...result.command.schema,
1090
+ flags: { ...propagated, ...result.command.schema.flags },
1091
+ }
1092
+ : undefined;
1093
+
1094
+ const meta = buildMeta(this.schema, helpOptions, result.command.schema.name);
1095
+ const commandRunOptions = buildCommandRunOptions(effectiveOptions, helpOptions, meta);
1096
+ return result.command._execute(result.remainingArgv, {
1097
+ ...commandRunOptions,
1098
+ ...(mergedSchema !== undefined ? { mergedSchema } : {}),
1099
+ });
1100
+ }
1101
+ }
1102
+ }
1103
+
1104
+ /**
1105
+ * Run the CLI program as a production entry point.
1106
+ *
1107
+ * Reads argv from the runtime adapter, dispatches to the matched
1108
+ * command, writes output to real streams, and exits the process.
1109
+ *
1110
+ * This is the **only** place that touches process state (via the
1111
+ * adapter). For testing, use `.execute()` instead — or provide a
1112
+ * test adapter via `options.adapter`.
1113
+ *
1114
+ * Defaults to `createAdapter()` when no adapter is provided,
1115
+ * which auto-detects the runtime (Node.js, Bun) and creates
1116
+ * the appropriate adapter.
1117
+ *
1118
+ * @param options - Optional runtime configuration including adapter.
1119
+ */
1120
+ async run(options?: CLIRunOptions): Promise<never> {
1121
+ const adapter = options?.adapter ?? createAdapter();
1122
+ const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : undefined;
1123
+
1124
+ const rawArgv = adapter.argv.slice(2);
1125
+
1126
+ // Extract --config <path> / --config=<path> before command dispatch (requires I/O via adapter)
1127
+ const { configPath, filteredArgv } = extractConfigFlag(rawArgv);
1128
+
1129
+ // Detect --json early for error rendering during config loading
1130
+ const hasJsonFlag = filteredArgv.includes('--json');
1131
+ const jsonMode = hasJsonFlag || options?.jsonMode === true;
1132
+
1133
+ // Config discovery (only when .config() was called on the builder)
1134
+ // Skip for completions subcommand — shell completions don't need config.
1135
+ // Resolve the first argv token against registered commands (by name + aliases)
1136
+ // so aliases or shadowed names are handled correctly.
1137
+ // When no subcommand token is present and a default command exists, check
1138
+ // whether the default command is 'completions' (unlikely but correct).
1139
+ const firstToken = filteredArgv[0];
1140
+ const matchedCommand =
1141
+ firstToken !== undefined
1142
+ ? this.schema.commands.find(
1143
+ (c) => c.schema.name === firstToken || c.schema.aliases.includes(firstToken),
1144
+ )
1145
+ : undefined;
1146
+ const effectiveCommandName =
1147
+ matchedCommand?.schema.name ?? this.schema.defaultCommand?.schema.name;
1148
+ const isCompletions = effectiveCommandName === 'completions';
1149
+ let loadedConfig: Readonly<Record<string, unknown>> | undefined;
1150
+
1151
+ if (
1152
+ this.schema.configSettings !== undefined &&
1153
+ !isCompletions &&
1154
+ options?.config === undefined
1155
+ ) {
1156
+ try {
1157
+ const result = await discoverConfig(this.schema.configSettings.appName, adapter, {
1158
+ ...(configPath !== undefined ? { configPath } : {}),
1159
+ ...(this.schema.configSettings.loaders !== undefined
1160
+ ? { loaders: this.schema.configSettings.loaders }
1161
+ : {}),
1162
+ });
1163
+ if (result.found) {
1164
+ loadedConfig = result.data;
1165
+ }
1166
+ } catch (err: unknown) {
1167
+ // Config errors are fatal — render and exit
1168
+ if (err instanceof CLIError) {
1169
+ if (jsonMode) {
1170
+ adapter.stdout(`${JSON.stringify({ error: err.toJSON() })}\n`);
1171
+ } else {
1172
+ adapter.stderr(`Error: ${err.message}\n`);
1173
+ if (err.suggest !== undefined) {
1174
+ adapter.stderr(`Suggestion: ${err.suggest}\n`);
1175
+ }
1176
+ }
1177
+ return adapter.exit(err.exitCode);
1178
+ }
1179
+ throw err;
1180
+ }
1181
+ }
1182
+
1183
+ // Package.json discovery (only when .packageJson() was called)
1184
+ // Skip for completions subcommand — no metadata needed.
1185
+ const packageJsonSettings = this.schema.packageJsonSettings;
1186
+ const builderWithPackageJson =
1187
+ packageJsonSettings !== undefined && !isCompletions
1188
+ ? await (async (): Promise<CLIBuilder> => {
1189
+ const pkg = await discoverPackageJson(adapter);
1190
+ if (pkg === null) return this;
1191
+
1192
+ const schema = this.schema;
1193
+ const inferredName = packageJsonSettings.inferName ? inferCliName(pkg) : undefined;
1194
+ return new CLIBuilder({
1195
+ ...schema,
1196
+ // Explicit > discovered: only fill in undefined fields
1197
+ ...(schema.version === undefined && pkg.version !== undefined
1198
+ ? { version: pkg.version }
1199
+ : {}),
1200
+ ...(schema.description === undefined && pkg.description !== undefined
1201
+ ? { description: pkg.description }
1202
+ : {}),
1203
+ ...(inferredName !== undefined ? { name: inferredName } : {}),
1204
+ });
1205
+ })()
1206
+ : this;
1207
+ const effectiveBuilder =
1208
+ inheritedName !== undefined
1209
+ ? new CLIBuilder({ ...builderWithPackageJson.schema, name: inheritedName })
1210
+ : builderWithPackageJson;
1211
+
1212
+ // Auto-create terminal prompter when stdin is a TTY and no explicit prompter provided.
1213
+ // This is the prompt gating seam: non-interactive environments (CI, piped stdin)
1214
+ // get stdinIsTTY=false → no auto-prompter → prompts skipped → falls through to default/required.
1215
+ const autoPrompter =
1216
+ options?.prompter === undefined && adapter.stdinIsTTY
1217
+ ? createTerminalPrompter(adapter.stdin, adapter.stderr)
1218
+ : undefined;
1219
+ const adapterStdinData =
1220
+ options?.stdinData === undefined && invocationNeedsStdin(effectiveBuilder, filteredArgv)
1221
+ ? await adapter.readStdin()
1222
+ : undefined;
1223
+
1224
+ // Source env, isTTY, and config from adapter when not explicitly provided in options
1225
+ const executeOptions: CLIRunOptions = {
1226
+ ...options,
1227
+ ...(options?.env === undefined ? { env: adapter.env } : {}),
1228
+ ...(options?.isTTY === undefined ? { isTTY: adapter.isTTY } : {}),
1229
+ ...(adapterStdinData !== undefined ? { stdinData: adapterStdinData } : {}),
1230
+ ...(autoPrompter !== undefined ? { prompter: autoPrompter } : {}),
1231
+ ...(loadedConfig !== undefined ? { config: loadedConfig } : {}),
1232
+ out: createOutput({
1233
+ stdout: adapter.stdout,
1234
+ stderr: adapter.stderr,
1235
+ jsonMode,
1236
+ isTTY: options?.isTTY ?? adapter.isTTY,
1237
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
1238
+ }),
1239
+ };
1240
+ const result = await effectiveBuilder.execute(filteredArgv, executeOptions);
1241
+
1242
+ // Write captured output to real streams via adapter
1243
+ for (const line of result.stdout) {
1244
+ adapter.stdout(line);
1245
+ }
1246
+ for (const line of result.stderr) {
1247
+ adapter.stderr(line);
1248
+ }
1249
+
1250
+ return adapter.exit(result.exitCode);
1251
+ }
1252
+ }
1253
+
1254
+ // --- Helpers
1255
+
1256
+ /**
1257
+ * Assemble a {@link RunResult} from its constituent parts.
1258
+ *
1259
+ * @param exitCode - Process exit code (0 = success).
1260
+ * @param captured - Captured stdout/stderr/activity buffers.
1261
+ * @param error - The originating error, if any.
1262
+ * @returns Structured run result.
1263
+ *
1264
+ * @internal
1265
+ */
1266
+ function buildResult(
1267
+ exitCode: number,
1268
+ captured: CapturedOutput,
1269
+ error: CLIError | undefined,
1270
+ ): RunResult {
1271
+ return {
1272
+ exitCode,
1273
+ stdout: captured.stdout,
1274
+ stderr: captured.stderr,
1275
+ activity: captured.activity,
1276
+ error,
1277
+ };
1278
+ }
1279
+
1280
+ const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
1281
+
1282
+ /**
1283
+ * Extract the final path segment from a path-like or URL-like string.
1284
+ *
1285
+ * @param input - Forward- or backslash-delimited path.
1286
+ * @returns Trailing segment, or `undefined` when the input is empty or slash-only.
1287
+ *
1288
+ * @internal
1289
+ */
1290
+ function basename(input: string): string | undefined {
1291
+ const trimmed = input.replace(/[\\/]+$/g, '');
1292
+ if (trimmed.length === 0) return undefined;
1293
+ const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
1294
+ const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
1295
+ return name.length > 0 ? name : undefined;
1296
+ }
1297
+
1298
+ /**
1299
+ * Detect known interpreter/runtime binary names (node, bun, deno, tsx).
1300
+ *
1301
+ * @param input - Candidate binary name, with or without `.exe` suffix.
1302
+ * @returns `true` when `input` matches a known runtime after normalization.
1303
+ *
1304
+ * @internal
1305
+ */
1306
+ function isRuntimeBinaryName(input: string): boolean {
1307
+ const normalized = input.toLowerCase().replace(/\.exe$/i, '');
1308
+ return RUNTIME_BINARIES.has(normalized);
1309
+ }
1310
+
1311
+ /**
1312
+ * Infer the displayed CLI name from the current runtime invocation.
1313
+ *
1314
+ * Resolution order:
1315
+ * 1. Node/Bun/tsx-style interpreters → script/entry argument basename
1316
+ * 2. Standalone executable invocations → argv[0] basename
1317
+ * 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
1318
+ *
1319
+ * @param argv - Full process argv (typically `process.argv` or adapter equivalent).
1320
+ * @returns Inferred program name, or `undefined` when inference is ambiguous.
1321
+ *
1322
+ * @internal
1323
+ */
1324
+ function inferInvocationName(argv: readonly string[]): string | undefined {
1325
+ const argv0 = argv[0];
1326
+ const argv1 = argv[1];
1327
+ const runtimeName = argv0 !== undefined ? basename(argv0) : undefined;
1328
+
1329
+ if (runtimeName !== undefined && isRuntimeBinaryName(runtimeName)) {
1330
+ if (runtimeName === 'bun' && argv1 === 'run') {
1331
+ const entryArg = argv[2];
1332
+ if (entryArg === undefined || entryArg.startsWith('-')) return undefined;
1333
+ return basename(entryArg);
1334
+ }
1335
+ if (runtimeName === 'deno' && argv1 === 'run') return undefined;
1336
+ if (argv1 === undefined || argv1.startsWith('-')) return undefined;
1337
+ return basename(argv1);
1338
+ }
1339
+
1340
+ return argv0 !== undefined ? basename(argv0) : undefined;
1341
+ }
1342
+
1343
+ // --- Factory function
1344
+
1345
+ /**
1346
+ * Options for the `cli({...})` factory form.
1347
+ *
1348
+ * This form is useful when the displayed CLI name should be inferred from the
1349
+ * current runtime invocation instead of always being hard-coded.
1350
+ */
1351
+ interface CLIOptions {
1352
+ /**
1353
+ * Explicit fallback CLI name.
1354
+ *
1355
+ * Used by `.execute()`, and by `.run()` when runtime name inheritance is
1356
+ * disabled or the invocation name cannot be inferred.
1357
+ *
1358
+ * @defaultValue `'cli'`
1359
+ */
1360
+ readonly name?: string;
1361
+
1362
+ /**
1363
+ * Replace `name` with the invoked program basename during `.run()`.
1364
+ *
1365
+ * Examples:
1366
+ * - `node ./bin/mycli.ts` → `mycli.ts`
1367
+ * - `/usr/local/bin/mycli` → `mycli`
1368
+ *
1369
+ * @defaultValue `false`
1370
+ */
1371
+ readonly inherit?: boolean;
1372
+ }
1373
+
1374
+ /**
1375
+ * Create a new CLI program builder.
1376
+ *
1377
+ * The CLI name is used in help text, usage lines, and generated completion scripts.
1378
+ *
1379
+ * @param nameOrOptions - Either the explicit CLI name or factory options.
1380
+ *
1381
+ * @example
1382
+ * ```ts
1383
+ * cli('mycli')
1384
+ * .version('1.0.0')
1385
+ * .description('My awesome tool')
1386
+ * .command(deploy)
1387
+ * .command(login)
1388
+ * .run();
1389
+ *
1390
+ * cli({ inherit: true })
1391
+ * .command(deploy)
1392
+ * .run();
1393
+ * ```
1394
+ */
1395
+
1396
+ function cli(name: string): CLIBuilder;
1397
+ function cli(options: CLIOptions): CLIBuilder;
1398
+ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1399
+ const name = typeof nameOrOptions === 'string' ? nameOrOptions : (nameOrOptions.name ?? 'cli');
1400
+ const inheritName = typeof nameOrOptions === 'string' ? false : (nameOrOptions.inherit ?? false);
1401
+
1402
+ return new CLIBuilder({
1403
+ name,
1404
+ inheritName,
1405
+ version: undefined,
1406
+ description: undefined,
1407
+ commands: [],
1408
+ defaultCommand: undefined,
1409
+ configSettings: undefined,
1410
+ packageJsonSettings: undefined,
1411
+ plugins: [],
1412
+ });
1413
+ }
1414
+
1415
+ // --- Exports
1416
+
1417
+ export type {
1418
+ BeforeParseParams,
1419
+ CLIPlugin,
1420
+ CLIPluginHooks,
1421
+ PluginCommandContext,
1422
+ ResolvedCommandParams,
1423
+ } from './plugin.ts';
1424
+ export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
1425
+ export { CLIBuilder, cli, formatRootHelp, plugin };