@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,1263 @@
1
+ /**
2
+ * Command schema builder with flag/arg composition and type accumulation.
3
+ *
4
+ * The `command()` factory returns an immutable `CommandBuilder` whose generic
5
+ * parameters track accumulated flag and arg builder types. Chaining `.flag()`
6
+ * and `.arg()` calls produces progressively narrower types. The `.action()`
7
+ * handler receives fully typed `{ args, flags, ctx, out }`.
8
+ *
9
+ * @module dreamcli/core/schema/command
10
+ */
11
+ import { CLIError } from '#internals/core/errors/index.ts';
12
+ import type {
13
+ ProgressHandle,
14
+ ProgressOptions,
15
+ SpinnerHandle,
16
+ SpinnerOptions,
17
+ TableColumn,
18
+ TableOptions,
19
+ } from './activity.ts';
20
+ import type { ArgBuilder, ArgConfig, ArgSchema, InferArgs } from './arg.ts';
21
+ import type { FlagBuilder, FlagConfig, FlagSchema, InferFlags } from './flag.ts';
22
+ import type { ErasedMiddlewareHandler, Middleware } from './middleware.ts';
23
+ import type { PromptConfig } from './prompt.ts';
24
+ import type { RunOptions, RunResult } from './run.ts';
25
+
26
+ // --- Context type utilities
27
+
28
+ /**
29
+ * Widen the context type when adding middleware.
30
+ *
31
+ * The default `C = Record<string, never>` uses an index signature where
32
+ * every key maps to `never` — making property access a type error until
33
+ * middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
34
+ * collapses all properties to `never` because `never & T = never`.
35
+ *
36
+ * This utility replaces `Record<string, never>` entirely on the first
37
+ * `.middleware()` call. Subsequent calls use plain intersection.
38
+ */
39
+ type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> =
40
+ C extends Record<string, never> ? Output : C & Output;
41
+
42
+ /**
43
+ * Widen the context type when adding command-scoped derived context.
44
+ *
45
+ * Validation-only derive handlers return `undefined`, preserving `C`.
46
+ * Context-producing derive handlers return an object that merges into `C`
47
+ * using the same first-call replacement rules as middleware.
48
+ */
49
+ type WidenDerivedContext<C extends Record<string, unknown>, Output> =
50
+ Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
51
+
52
+ // --- Type-level configuration (phantom state tracked through the chain)
53
+
54
+ /**
55
+ * Compile-time state carried through the command builder chain.
56
+ *
57
+ * `F` accumulates named flag builders; `A` accumulates named arg builders.
58
+ * Both start empty (`{}`) and grow as `.flag()` / `.arg()` are called.
59
+ */
60
+ interface CommandConfig {
61
+ readonly flags: Record<string, FlagBuilder<FlagConfig>>;
62
+ readonly args: Record<string, ArgBuilder<ArgConfig>>;
63
+ }
64
+
65
+ // --- Interactive resolver types
66
+
67
+ /**
68
+ * Parameters received by the interactive resolver function.
69
+ *
70
+ * `flags` contains partially resolved values — present for flags resolved
71
+ * via CLI, env, or config, `undefined` for unresolved flags. The resolver
72
+ * uses this to decide which prompts to show based on current state.
73
+ */
74
+ interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
75
+ /** Partially resolved flag values (after CLI/env/config, before prompts). */
76
+ readonly flags: Readonly<Partial<InferFlags<F>>>;
77
+ }
78
+
79
+ /**
80
+ * A record mapping flag names to prompt configs or falsy values.
81
+ *
82
+ * - `PromptConfig` — show this prompt for the flag
83
+ * - `false | undefined | null | 0 | ''` — skip prompting for this flag
84
+ *
85
+ * Only flag names that need prompting should have truthy values.
86
+ * Flags not mentioned are handled by their per-flag `.prompt()` config.
87
+ */
88
+ type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
89
+
90
+ /**
91
+ * Interactive resolver function for command-level prompt control.
92
+ *
93
+ * Called after CLI/env/config resolution but before per-flag prompts fire.
94
+ * Receives partially resolved values and returns a prompt schema for
95
+ * flags that should be prompted. Commands without `.interactive()` use
96
+ * per-flag prompt configs directly.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * const deploy = command('deploy')
101
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
102
+ * .interactive(({ flags }) => ({
103
+ * region: !flags.region && {
104
+ * kind: 'select',
105
+ * message: 'Select region',
106
+ * },
107
+ * }))
108
+ * .action(({ flags }) => { ... });
109
+ * ```
110
+ */
111
+ type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (
112
+ params: InteractiveParams<F>,
113
+ ) => InteractiveResult;
114
+
115
+ /**
116
+ * Type-erased interactive resolver stored on `CommandSchema`.
117
+ *
118
+ * Advanced bridge type: most consumers should use {@link InteractiveResolver}
119
+ * via `command().interactive(...)` and never reference this alias directly.
120
+ *
121
+ * At runtime, the resolver receives `{ flags: Record<string, unknown> }`
122
+ * and returns `Record<string, PromptConfig | falsy>`. The phantom types
123
+ * from `CommandBuilder<F, A>` are erased.
124
+ *
125
+ * @internal
126
+ */
127
+ type ErasedInteractiveResolver = (params: {
128
+ readonly flags: Readonly<Record<string, unknown>>;
129
+ }) => InteractiveResult;
130
+
131
+ // --- Handler types
132
+
133
+ /**
134
+ * Output channel available inside action handlers.
135
+ *
136
+ * Provides structured methods for stdout/stderr, JSON output,
137
+ * spinners, progress bars, and tables. The real implementation lives in
138
+ * `src/core/output/`; this interface defines the shape that handlers consume.
139
+ */
140
+ interface Out {
141
+ /** Write to stdout (normal output). */
142
+ log(message: string): void;
143
+ /** Informational (may be suppressed in quiet mode). */
144
+ info(message: string): void;
145
+ /** Warning to stderr. */
146
+ warn(message: string): void;
147
+ /** Error to stderr. */
148
+ error(message: string): void;
149
+ /**
150
+ * Emit a structured JSON value to stdout.
151
+ *
152
+ * Always serialises `value` as JSON to stdout regardless of output
153
+ * mode. Prefer this over `log(JSON.stringify(...))` so the output
154
+ * channel can enforce consistent formatting and future features
155
+ * (pretty-print in TTY, streaming JSON, etc.).
156
+ */
157
+ json(value: unknown): void;
158
+ /**
159
+ * Whether the output channel is in JSON mode (`--json` flag active).
160
+ *
161
+ * Handlers can check this to skip decorative output (spinners,
162
+ * progress bars, ANSI formatting) when machine-readable output is
163
+ * expected.
164
+ */
165
+ readonly jsonMode: boolean;
166
+
167
+ /**
168
+ * Whether stdout is connected to a TTY (terminal).
169
+ *
170
+ * Handlers can check this to decide whether to emit decorative output
171
+ * (spinners, progress bars, ANSI color codes). When `false`, the output
172
+ * is being piped or redirected — skip interactive decorations.
173
+ *
174
+ * Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
175
+ * decorative output should be suppressed regardless of `isTTY`.
176
+ */
177
+ readonly isTTY: boolean;
178
+
179
+ /**
180
+ * Render tabular data.
181
+ *
182
+ * - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
183
+ * - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
184
+ * - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
185
+ * (useful for `grep`, `awk`, etc.).
186
+ * - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
187
+ * side channel while `json()` writes machine output to stdout.
188
+ *
189
+ * When `columns` is omitted, columns are auto-inferred from the keys
190
+ * of the first row. Column headers default to the key name.
191
+ *
192
+ * When `columns` is provided, both text and JSON output are projected to
193
+ * only the listed keys.
194
+ *
195
+ * @param rows - Array of row objects.
196
+ */
197
+ table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
198
+ /**
199
+ * Render tabular data with explicit column selection.
200
+ *
201
+ * @param rows - Array of row objects.
202
+ * @param columns - Column descriptors controlling which keys are shown and header labels.
203
+ * @param options - Per-call rendering options (format, stream).
204
+ */
205
+ table<T extends Record<string, unknown>>(
206
+ rows: readonly T[],
207
+ columns?: readonly TableColumn<T>[],
208
+ options?: TableOptions,
209
+ ): void;
210
+
211
+ /**
212
+ * Create a spinner for indeterminate progress feedback.
213
+ *
214
+ * Returns a handle for lifecycle control. In non-TTY/jsonMode,
215
+ * returns a no-op handle (or static fallback if configured).
216
+ *
217
+ * @param text - Initial spinner text.
218
+ * @param options - Fallback strategy for non-TTY environments.
219
+ * @returns A {@link SpinnerHandle} for lifecycle control.
220
+ */
221
+ spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
222
+
223
+ /**
224
+ * Create a progress bar for measured work.
225
+ *
226
+ * Returns a handle for updating progress. Pass `total` for
227
+ * determinate mode (percentage bar); omit for indeterminate (pulsing).
228
+ *
229
+ * @param options - Progress configuration (total, label, fallback).
230
+ * @returns A {@link ProgressHandle} for updating progress.
231
+ */
232
+ progress(options: ProgressOptions): ProgressHandle;
233
+
234
+ /**
235
+ * Stop the currently active spinner or progress handle, if any.
236
+ *
237
+ * TTY spinner and progress handles start `setInterval` timers that
238
+ * prevent the process from exiting until a terminal method (`stop`,
239
+ * `succeed`, `fail`, `done`) is called. If a handler throws before
240
+ * reaching that call, the timer leaks and the process hangs.
241
+ *
242
+ * Call `stopActive()` in a `finally` block after handler execution
243
+ * to guarantee cleanup. It is idempotent — safe to call when no
244
+ * handle is active, or when the handle was already stopped.
245
+ *
246
+ * The framework calls this automatically in `runCommand()` and
247
+ * `cli.run()`. Direct users of `createOutput()` should call it
248
+ * themselves after the handler returns or throws.
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * const out = createOutput({ isTTY: true });
253
+ * try {
254
+ * await handler({ out });
255
+ * } finally {
256
+ * out.stopActive();
257
+ * }
258
+ * ```
259
+ */
260
+ stopActive(): void;
261
+ }
262
+
263
+ /**
264
+ * Runtime metadata about the CLI program and current command execution.
265
+ *
266
+ * Available to action handlers and middleware.
267
+ *
268
+ * Populated by the CLI dispatch layer from {@link CLISchema} and
269
+ * {@link CommandSchema}. For standalone `runCommand()` calls without
270
+ * a CLI wrapper, a minimal meta is constructed from the command's own schema.
271
+ */
272
+ interface CommandMeta {
273
+ /** CLI program name (from `cli('name')` or package.json inference). */
274
+ readonly name: string;
275
+ /** Binary display name used in help/usage (may differ from `name`). */
276
+ readonly bin: string;
277
+ /** Program version, if set via `.version()` or discovered from package.json. */
278
+ readonly version: string | undefined;
279
+ /** The leaf command name currently being executed. */
280
+ readonly command: string;
281
+ }
282
+
283
+ /**
284
+ * The bag of values received by an action handler.
285
+ *
286
+ * - `args` — fully resolved positional arguments
287
+ * - `flags` — fully resolved flags
288
+ * - `ctx` — derive/middleware-provided context
289
+ * - `out` — output channel
290
+ * - `meta` — CLI program metadata (name, bin, version, command)
291
+ *
292
+ * The `C` parameter defaults to `Record<string, never>`, making `ctx`
293
+ * property access a type error until derive or middleware extends it.
294
+ */
295
+ interface ActionParams<
296
+ F extends Record<string, FlagBuilder<FlagConfig>>,
297
+ A extends Record<string, ArgBuilder<ArgConfig>>,
298
+ C extends Record<string, unknown> = Record<string, never>,
299
+ > {
300
+ readonly args: Readonly<InferArgs<A>>;
301
+ readonly flags: Readonly<InferFlags<F>>;
302
+ readonly ctx: Readonly<C>;
303
+ readonly out: Out;
304
+ readonly meta: CommandMeta;
305
+ }
306
+
307
+ /**
308
+ * Action handler function signature.
309
+ *
310
+ * May be sync or async — the framework will `await` the return value
311
+ * regardless. The `C` parameter carries the accumulated middleware
312
+ * context type (defaults to empty).
313
+ */
314
+ type ActionHandler<
315
+ F extends Record<string, FlagBuilder<FlagConfig>>,
316
+ A extends Record<string, ArgBuilder<ArgConfig>>,
317
+ C extends Record<string, unknown> = Record<string, never>,
318
+ > = (params: ActionParams<F, A, C>) => void | Promise<void>;
319
+
320
+ /**
321
+ * The bag of values received by a derive handler.
322
+ *
323
+ * Identical to {@link ActionParams}: derives run after full resolution and
324
+ * before the action handler, with typed args/flags/current context plus `out`
325
+ * and `meta`.
326
+ */
327
+ type DeriveParams<
328
+ F extends Record<string, FlagBuilder<FlagConfig>>,
329
+ A extends Record<string, ArgBuilder<ArgConfig>>,
330
+ C extends Record<string, unknown> = Record<string, never>,
331
+ > = ActionParams<F, A, C>;
332
+
333
+ /**
334
+ * Command-scoped typed pre-action handler.
335
+ *
336
+ * Derive handlers may:
337
+ * - validate resolved input and throw `CLIError`
338
+ * - return `undefined` to continue without changing context
339
+ * - return an object whose properties merge into `ctx` downstream
340
+ *
341
+ * They cannot wrap downstream execution; use `middleware()` for that.
342
+ */
343
+ type DeriveHandler<
344
+ F extends Record<string, FlagBuilder<FlagConfig>>,
345
+ A extends Record<string, ArgBuilder<ArgConfig>>,
346
+ C extends Record<string, unknown> = Record<string, never>,
347
+ Output extends Record<string, unknown> | undefined = undefined,
348
+ > = (params: DeriveParams<F, A, C>) => Output | Promise<Output>;
349
+
350
+ /**
351
+ * Type-erased derive handler stored on the command builder.
352
+ *
353
+ * @internal
354
+ */
355
+ type ErasedDeriveHandler = (params: {
356
+ readonly args: Readonly<Record<string, unknown>>;
357
+ readonly flags: Readonly<Record<string, unknown>>;
358
+ readonly ctx: Readonly<Record<string, unknown>>;
359
+ readonly out: Out;
360
+ readonly meta: CommandMeta;
361
+ }) =>
362
+ | undefined
363
+ | Readonly<Record<string, unknown>>
364
+ | Promise<undefined | Readonly<Record<string, unknown>>>;
365
+
366
+ /**
367
+ * Internal execution step union preserving registration order across
368
+ * `derive()` and `middleware()`.
369
+ *
370
+ * @internal
371
+ */
372
+ type ExecutionStep =
373
+ | {
374
+ readonly kind: 'derive';
375
+ readonly handler: ErasedDeriveHandler;
376
+ }
377
+ | {
378
+ readonly kind: 'middleware';
379
+ readonly handler: ErasedMiddlewareHandler;
380
+ };
381
+
382
+ // --- Runtime schema data
383
+
384
+ /** A single usage example shown in help text. */
385
+ interface CommandExample {
386
+ /** The command invocation (e.g. `'deploy production --force'`). */
387
+ readonly command: string;
388
+ /** Optional description of what this example does. */
389
+ readonly description?: string;
390
+ }
391
+
392
+ /**
393
+ * Runtime descriptor produced by {@link CommandBuilder}.
394
+ *
395
+ * Consumers (parser, help generator, CLI dispatcher) read this to
396
+ * understand the command's shape — flags, args, aliases, subcommands,
397
+ * middleware, and interactive resolver.
398
+ */
399
+ interface CommandSchema {
400
+ /** The command name (used for dispatch, e.g. `'deploy'`). */
401
+ readonly name: string;
402
+ /** Human-readable description for help text. */
403
+ readonly description: string | undefined;
404
+ /** Alternative names for this command. */
405
+ readonly aliases: readonly string[];
406
+ /** Whether this command is hidden from help listings. */
407
+ readonly hidden: boolean;
408
+ /** Usage examples for help text. */
409
+ readonly examples: readonly CommandExample[];
410
+ /** Named flag schemas, keyed by flag name. */
411
+ readonly flags: Readonly<Record<string, FlagSchema>>;
412
+ /** Ordered positional arg entries (name + schema). */
413
+ readonly args: readonly CommandArgEntry[];
414
+ /** Whether an action handler has been registered. */
415
+ readonly hasAction: boolean;
416
+ /**
417
+ * Command-level interactive resolver for schema-driven prompt control.
418
+ *
419
+ * When set, called after CLI/env/config resolution with partially resolved
420
+ * flag values. Returns prompt configs for flags that need interactive input.
421
+ * Takes precedence over per-flag `.prompt()` configs for flags it returns
422
+ * configs for; flags not mentioned fall back to their per-flag configs.
423
+ *
424
+ * @see InteractiveResolver
425
+ */
426
+ readonly interactive: ErasedInteractiveResolver | undefined;
427
+ /**
428
+ * Middleware handlers to run before the action handler.
429
+ *
430
+ * Executed in registration order — first middleware registered runs
431
+ * first and calls `next()` to proceed to subsequent middleware,
432
+ * ending with the action handler. Context accumulates via intersection
433
+ * at the type level and via object spread at runtime.
434
+ */
435
+ readonly middleware: readonly ErasedMiddlewareHandler[];
436
+ /**
437
+ * Nested subcommand schemas (for help rendering and completion).
438
+ *
439
+ * Pure data — no execution closures. Populated by `.command()` on
440
+ * `CommandBuilder`. Empty for leaf commands.
441
+ */
442
+ readonly commands: readonly CommandSchema[];
443
+ }
444
+
445
+ /**
446
+ * A named positional argument entry in the command schema.
447
+ *
448
+ * Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
449
+ * The array ordering in {@link CommandSchema.args} determines CLI position.
450
+ */
451
+ interface CommandArgEntry {
452
+ readonly name: string;
453
+ readonly schema: ArgSchema;
454
+ }
455
+
456
+ /**
457
+ * Validate a new arg entry against invariants before adding it to the command.
458
+ *
459
+ * @param name - Arg name being registered.
460
+ * @param schema - Runtime descriptor of the arg.
461
+ * @param args - Already-registered arg entries on this command.
462
+ *
463
+ * @throws {@link CLIError} `INVALID_BUILDER_STATE` if both `.stdin()` and `.variadic()` are set.
464
+ * @throws {@link CLIError} `DUPLICATE_STDIN_ARG` if another arg already uses `.stdin()`.
465
+ *
466
+ * @internal
467
+ */
468
+ function validateArgEntry(name: string, schema: ArgSchema, args: readonly CommandArgEntry[]): void {
469
+ if (schema.stdinMode && schema.variadic) {
470
+ throw new CLIError(`Argument <${name}> cannot be both variadic and stdin-backed`, {
471
+ code: 'INVALID_BUILDER_STATE',
472
+ details: { arg: name, stdinMode: true, variadic: true },
473
+ suggest: 'Remove .stdin() or .variadic() from this argument',
474
+ });
475
+ }
476
+
477
+ if (!schema.stdinMode) {
478
+ return;
479
+ }
480
+
481
+ const existing = args.find((entry) => entry.schema.stdinMode);
482
+ if (existing === undefined) {
483
+ return;
484
+ }
485
+
486
+ throw new CLIError(
487
+ `Only one stdin argument is allowed; <${existing.name}> is already stdin-backed`,
488
+ {
489
+ code: 'DUPLICATE_STDIN_ARG',
490
+ details: { arg: name, existingArg: existing.name },
491
+ suggest: 'Keep .stdin() on a single argument per command',
492
+ },
493
+ );
494
+ }
495
+
496
+ // --- Type-erased command interface (shared between schema and CLI layers)
497
+
498
+ /**
499
+ * A type-erased command entry for heterogeneous command storage.
500
+ *
501
+ * Advanced/internal bridge type: most consumers should work with
502
+ * {@link CommandBuilder} and never reference `ErasedCommand` directly.
503
+ *
504
+ * Commands registered via `CLIBuilder.command()` have heterogeneous `F`, `A`,
505
+ * and `C` type parameters. At the dispatch level we only need the runtime
506
+ * schema (for name/alias matching and help) and the ability to delegate to
507
+ * `runCommand()`. This interface captures exactly that contract.
508
+ *
509
+ * The `_execute` function closes over the original typed `CommandBuilder`,
510
+ * preserving full type safety inside the closure while presenting a
511
+ * uniform interface to the dispatcher.
512
+ *
513
+ * Defined here (rather than in the CLI layer) so both `CommandBuilder` and
514
+ * `CLIBuilder` can reference it without circular imports.
515
+ *
516
+ * @internal
517
+ */
518
+ interface ErasedCommand {
519
+ /** Runtime schema for name matching and help rendering. */
520
+ readonly schema: CommandSchema;
521
+ /**
522
+ * Nested subcommands (name/alias → erased child).
523
+ *
524
+ * Built recursively by `eraseCommand()` in the CLI layer.
525
+ * Empty map for leaf commands. The dispatch layer uses this for
526
+ * recursive command tree traversal.
527
+ *
528
+ * @internal
529
+ */
530
+ readonly subcommands: ReadonlyMap<string, ErasedCommand>;
531
+ /** Execute this command against argv. Closes over the typed CommandBuilder. */
532
+ readonly _execute: (argv: readonly string[], options?: RunOptions) => Promise<RunResult>;
533
+ }
534
+
535
+ // --- Type-erased builder alias (for heterogeneous subcommand storage)
536
+
537
+ /**
538
+ * Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
539
+ *
540
+ * Advanced helper alias: useful only when working on DreamCLI internals or
541
+ * custom tooling that mirrors the framework's type-erasure boundary.
542
+ *
543
+ * Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
544
+ * assignable. The CLI layer's `eraseCommand()` traverses these to build
545
+ * the execution tree.
546
+ *
547
+ * @internal
548
+ */
549
+ type AnyCommandBuilder = CommandBuilder<
550
+ Record<string, FlagBuilder<FlagConfig>>,
551
+ Record<string, ArgBuilder<ArgConfig>>,
552
+ Record<string, unknown>
553
+ >;
554
+
555
+ /**
556
+ * Erase a typed `CommandBuilder<F, A, C>` to `AnyCommandBuilder` for
557
+ * heterogeneous storage. Centralises the `as unknown as` double-cast
558
+ * required at the type-erasure boundary.
559
+ *
560
+ * @internal
561
+ */
562
+ function eraseBuilder<
563
+ F extends Record<string, FlagBuilder<FlagConfig>>,
564
+ A extends Record<string, ArgBuilder<ArgConfig>>,
565
+ C extends Record<string, unknown>,
566
+ >(builder: CommandBuilder<F, A, C>): AnyCommandBuilder {
567
+ return builder as unknown as AnyCommandBuilder;
568
+ }
569
+
570
+ // --- CommandBuilder — immutable builder with type-level tracking
571
+
572
+ /**
573
+ * Immutable command schema builder.
574
+ *
575
+ * The type parameters `F` (flags), `A` (args), and `C` (context) are
576
+ * phantom types that accumulate builder types as `.flag()`, `.arg()`,
577
+ * `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
578
+ * fully typed `ActionParams<F, A, C>`.
579
+ *
580
+ * `C` defaults to `Record<string, never>`, making `ctx` property
581
+ * access a type error until derive or middleware extends it.
582
+ *
583
+ * @example
584
+ * ```ts
585
+ * const deploy = command('deploy')
586
+ * .description('Deploy to an environment')
587
+ * .arg('target', arg.string().describe('Deploy target'))
588
+ * .flag('force', flag.boolean().alias('f'))
589
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
590
+ * .action(async ({ args, flags, out }) => {
591
+ * // args.target: string
592
+ * // flags.force: boolean
593
+ * // flags.region: 'us' | 'eu' | 'ap' | undefined
594
+ * out.log(`Deploying ${args.target}...`);
595
+ * });
596
+ * ```
597
+ */
598
+ class CommandBuilder<
599
+ /* biome-ignore lint/complexity/noBannedTypes: {} is the correct initial accumulator for intersection-based type growth (F & Record<N, B>) */ // deno-lint-ignore ban-types
600
+ F extends Record<string, FlagBuilder<FlagConfig>> = {},
601
+ /* biome-ignore lint/complexity/noBannedTypes: {} is the correct initial accumulator for intersection-based type growth (A & Record<N, B>) */ // deno-lint-ignore ban-types
602
+ A extends Record<string, ArgBuilder<ArgConfig>> = {},
603
+ C extends Record<string, unknown> = Record<string, never>,
604
+ > {
605
+ /** @internal Runtime schema descriptor. */
606
+ readonly schema: CommandSchema;
607
+
608
+ /** @internal The action handler, if registered. */
609
+ readonly handler: ActionHandler<F, A, C> | undefined;
610
+
611
+ /**
612
+ * @internal Nested sub-command builders (type-erased for heterogeneous storage).
613
+ *
614
+ * Stored separately from `schema.commands` because builders carry action
615
+ * handlers and phantom types needed by `eraseCommand()` in the CLI layer.
616
+ * `schema.commands` holds pure `CommandSchema[]` for help/completion.
617
+ */
618
+ readonly _subcommands: readonly AnyCommandBuilder[];
619
+
620
+ /**
621
+ * @internal Execution steps in registration order.
622
+ *
623
+ * Distinct from `schema.middleware`: middleware handlers remain in schema
624
+ * for backward compatibility, while derives stay command-local and builder-
625
+ * scoped so future shared/global middleware can compose cleanly.
626
+ */
627
+ readonly _executionSteps: readonly ExecutionStep[];
628
+
629
+ /**
630
+ * @internal Type brands — exist only in the type system (`declare`
631
+ * produces no runtime property). Used for type inference.
632
+ */
633
+ declare readonly _flags: F;
634
+ declare readonly _args: A;
635
+ declare readonly _ctx: C;
636
+
637
+ /**
638
+ * @param schema - Runtime command descriptor.
639
+ * @param handler - Action handler, if registered.
640
+ * @param subcommands - Nested sub-command builders (type-erased).
641
+ * @param executionSteps - Derive/middleware steps in registration order.
642
+ */
643
+ constructor(
644
+ schema: CommandSchema,
645
+ handler?: ActionHandler<F, A, C>,
646
+ subcommands?: readonly AnyCommandBuilder[],
647
+ executionSteps?: readonly ExecutionStep[],
648
+ ) {
649
+ this.schema = schema;
650
+ this.handler = handler;
651
+ this._subcommands = subcommands ?? [];
652
+ this._executionSteps = executionSteps ?? [];
653
+ }
654
+
655
+ // -- Interactive resolver ------------------------------------------------
656
+
657
+ /**
658
+ * Register a command-level interactive resolver for schema-driven prompts.
659
+ *
660
+ * The resolver is called after CLI/env/config resolution with partially
661
+ * resolved flag values. It returns a prompt schema for flags that need
662
+ * interactive input based on the current state.
663
+ *
664
+ * For flags the resolver returns a `PromptConfig`, that config is used
665
+ * instead of any per-flag `.prompt()` config. For flags returned as falsy
666
+ * (or not mentioned), per-flag `.prompt()` configs are used as fallback.
667
+ *
668
+ * Commands without `.interactive()` use per-flag prompt configs directly.
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * const deploy = command('deploy')
673
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
674
+ * .flag('force', flag.boolean())
675
+ * .interactive(({ flags }) => ({
676
+ * region: !flags.region && {
677
+ * kind: 'select',
678
+ * message: 'Select region',
679
+ * },
680
+ * }))
681
+ * .action(({ flags }) => { ... });
682
+ * ```
683
+ *
684
+ * @param resolver - Function receiving partially resolved flags and returning prompt configs.
685
+ * @returns The builder (for chaining).
686
+ */
687
+ interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C> {
688
+ // The resolver is type-erased for storage on CommandSchema.
689
+ // At runtime, `InteractiveResolver<F>` is just `(params: { flags }) => Record<...>`.
690
+ // The phantom types on F are erased — the resolver's runtime behaviour is
691
+ // identical to `ErasedInteractiveResolver`.
692
+ const erased = resolver as unknown as ErasedInteractiveResolver;
693
+ return new CommandBuilder(
694
+ { ...this.schema, interactive: erased },
695
+ this.handler,
696
+ this._subcommands,
697
+ this._executionSteps,
698
+ );
699
+ }
700
+
701
+ // -- Derive --------------------------------------------------------------
702
+
703
+ /**
704
+ * Register a command-scoped typed pre-action handler.
705
+ *
706
+ * Derive runs after full resolution and before the action handler.
707
+ * It receives typed `{ args, flags, ctx, out, meta }` and may either:
708
+ *
709
+ * - return `undefined` for validation-only behavior
710
+ * - return an object to merge additional properties into `ctx`
711
+ *
712
+ * Unlike middleware, derive cannot wrap downstream execution and does not
713
+ * use `next()`. Use `middleware()` for timing, logging, retries, cleanup,
714
+ * or error-boundary patterns.
715
+ *
716
+ * Adding derive drops the current handler (like `.flag()`, `.arg()`, and
717
+ * `.middleware()`) because the action handler's `ctx` type may change.
718
+ *
719
+ * @example
720
+ * ```ts
721
+ * command('deploy')
722
+ * .flag('token', flag.string().env('AUTH_TOKEN'))
723
+ * .derive(({ flags }) => {
724
+ * if (!flags.token) {
725
+ * throw new CLIError('Not authenticated', {
726
+ * code: 'AUTH_REQUIRED',
727
+ * suggest: 'Run `mycli login` or set AUTH_TOKEN',
728
+ * });
729
+ * }
730
+ * return { token: flags.token };
731
+ * })
732
+ * .action(({ ctx }) => {
733
+ * ctx.token; // string
734
+ * });
735
+ * ```
736
+ *
737
+ * @param handler - Derive function receiving typed args/flags/ctx.
738
+ * @returns The builder (for chaining).
739
+ */
740
+ derive<Output extends Record<string, unknown> | undefined>(
741
+ handler: DeriveHandler<F, A, C, Output>,
742
+ ): CommandBuilder<F, A, WidenDerivedContext<C, Output>> {
743
+ const erased = handler as unknown as ErasedDeriveHandler;
744
+ return new CommandBuilder<F, A, WidenDerivedContext<C, Output>>(
745
+ { ...this.schema, hasAction: false },
746
+ undefined,
747
+ this._subcommands,
748
+ [
749
+ ...this._executionSteps,
750
+ {
751
+ kind: 'derive',
752
+ handler: erased,
753
+ },
754
+ ],
755
+ );
756
+ }
757
+
758
+ // -- Middleware ----------------------------------------------------------
759
+
760
+ /**
761
+ * Register middleware to run before the action handler.
762
+ *
763
+ * Middleware executes in registration order. Each middleware receives
764
+ * `{ args, flags, ctx, out, next }` and must call `next(additions)`
765
+ * to continue the chain. Context additions are merged and become
766
+ * typed downstream.
767
+ *
768
+ * Adding middleware widens `C` via intersection and drops the current
769
+ * handler (like `.flag()` / `.arg()` — the handler's type signature
770
+ * changes when context changes).
771
+ *
772
+ * @example
773
+ * ```ts
774
+ * import { CLIError, command, middleware } from 'dreamcli';
775
+ *
776
+ * interface User {
777
+ * id: string;
778
+ * email: string;
779
+ * }
780
+ *
781
+ * async function getCurrentUser(): Promise<User | null> {
782
+ * return { id: 'u_123', email: 'dev@example.com' };
783
+ * }
784
+ *
785
+ * function startTrace(name: string): string {
786
+ * return `trace:${name}`;
787
+ * }
788
+ *
789
+ * // Resolve the current user and expose it as `ctx.user` downstream.
790
+ * const auth = middleware<{ user: User }>(async ({ next }) => {
791
+ * const user = await getCurrentUser();
792
+ * if (!user) {
793
+ * throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
794
+ * }
795
+ * await next({ user });
796
+ * });
797
+ *
798
+ * // Create a trace id for this command run and expose it as `ctx.traceId`.
799
+ * const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
800
+ * const traceId = startTrace(`${meta.name}.${meta.command}`);
801
+ * await next({ traceId });
802
+ * });
803
+ *
804
+ * command('deploy')
805
+ * .middleware(auth) // C becomes { user: User }
806
+ * .middleware(telemetry) // C becomes { user: User } & { traceId: string }
807
+ * .action(({ ctx }) => {
808
+ * ctx.user; // User — typed
809
+ * ctx.traceId; // string — typed
810
+ * });
811
+ * ```
812
+ *
813
+ * @param m - {@link Middleware} instance created via `middleware()`.
814
+ * @returns The builder (for chaining).
815
+ */
816
+ middleware<Output extends Record<string, unknown>>(
817
+ m: Middleware<Output>,
818
+ ): CommandBuilder<F, A, WidenContext<C, Output>> {
819
+ return new CommandBuilder(
820
+ {
821
+ ...this.schema,
822
+ middleware: [...this.schema.middleware, m._handler],
823
+ hasAction: false,
824
+ },
825
+ // Handler intentionally dropped — C changed, invalidating handler signature.
826
+ undefined,
827
+ this._subcommands,
828
+ [
829
+ ...this._executionSteps,
830
+ {
831
+ kind: 'middleware',
832
+ handler: m._handler,
833
+ },
834
+ ],
835
+ );
836
+ }
837
+
838
+ // -- Metadata modifiers --------------------------------------------------
839
+
840
+ /**
841
+ * Set the command's description for help text.
842
+ *
843
+ * Displayed below the usage line in `--help` output and next to the
844
+ * command name in parent command/group help listings.
845
+ *
846
+ * @param text - One-line description of what the command does.
847
+ *
848
+ * @example
849
+ * ```ts
850
+ * command('deploy')
851
+ * .description('Deploy the application to a target environment')
852
+ * .action(({ out }) => { out.log('deploying...'); });
853
+ *
854
+ * // $ mycli deploy --help
855
+ * // Usage: deploy [flags]
856
+ * //
857
+ * // Deploy the application to a target environment
858
+ * ```
859
+ *
860
+ * @returns The builder (for chaining).
861
+ */
862
+ description(text: string): CommandBuilder<F, A, C> {
863
+ return new CommandBuilder(
864
+ { ...this.schema, description: text },
865
+ this.handler,
866
+ this._subcommands,
867
+ this._executionSteps,
868
+ );
869
+ }
870
+
871
+ /**
872
+ * Add an alternative name for this command.
873
+ *
874
+ * Aliases are accepted during dispatch alongside the primary name.
875
+ * Multiple aliases can be chained. Aliases are shown in help output.
876
+ *
877
+ * @param name - Alternative command name (e.g. `'d'` for `deploy`).
878
+ *
879
+ * @example
880
+ * ```ts
881
+ * command('deploy')
882
+ * .alias('d')
883
+ * .alias('push')
884
+ * .action(({ out }) => { out.log('deploying...'); });
885
+ *
886
+ * // All equivalent:
887
+ * // $ mycli deploy
888
+ * // $ mycli d
889
+ * // $ mycli push
890
+ * ```
891
+ *
892
+ * @returns The builder (for chaining).
893
+ */
894
+ alias(name: string): CommandBuilder<F, A, C> {
895
+ return new CommandBuilder(
896
+ { ...this.schema, aliases: [...this.schema.aliases, name] },
897
+ this.handler,
898
+ this._subcommands,
899
+ this._executionSteps,
900
+ );
901
+ }
902
+
903
+ /**
904
+ * Hide this command from help listings.
905
+ *
906
+ * The command remains fully functional and dispatchable — it just
907
+ * won't appear in `--help` output or shell completions. Useful for
908
+ * internal/debug commands.
909
+ *
910
+ * @example
911
+ * ```ts
912
+ * command('debug-dump')
913
+ * .hidden()
914
+ * .action(({ out }) => { out.log(JSON.stringify(internalState)); });
915
+ *
916
+ * // $ mycli --help → 'debug-dump' is not listed
917
+ * // $ mycli debug-dump → still works
918
+ * ```
919
+ *
920
+ * @returns The builder (for chaining).
921
+ */
922
+ hidden(): CommandBuilder<F, A, C> {
923
+ return new CommandBuilder(
924
+ { ...this.schema, hidden: true },
925
+ this.handler,
926
+ this._subcommands,
927
+ this._executionSteps,
928
+ );
929
+ }
930
+
931
+ /**
932
+ * Add a usage example to help text.
933
+ *
934
+ * Examples are rendered in the "Examples:" section of `--help` output.
935
+ * Call multiple times to add several examples. Each example shows a
936
+ * shell invocation, optionally with a description.
937
+ *
938
+ * @param cmd - The example command line (without the program name prefix).
939
+ * @param description - Optional one-line explanation of what the example does.
940
+ *
941
+ * @example
942
+ * ```ts
943
+ * command('deploy')
944
+ * .arg('target', arg.string())
945
+ * .flag('force', flag.boolean().alias('f'))
946
+ * .example('deploy production', 'Deploy to production')
947
+ * .example('deploy staging -f', 'Force deploy to staging')
948
+ * .action(({ args, flags }) => { ... });
949
+ *
950
+ * // $ mycli deploy --help
951
+ * // ...
952
+ * // Examples:
953
+ * // deploy production Deploy to production
954
+ * // deploy staging -f Force deploy to staging
955
+ * ```
956
+ *
957
+ * @returns The builder (for chaining).
958
+ */
959
+ example(cmd: string, description?: string): CommandBuilder<F, A, C> {
960
+ const entry: CommandExample =
961
+ description !== undefined ? { command: cmd, description } : { command: cmd };
962
+ return new CommandBuilder(
963
+ { ...this.schema, examples: [...this.schema.examples, entry] },
964
+ this.handler,
965
+ this._subcommands,
966
+ this._executionSteps,
967
+ );
968
+ }
969
+
970
+ // -- Flag accumulation ---------------------------------------------------
971
+
972
+ /**
973
+ * Register a named flag on this command.
974
+ *
975
+ * The flag name is added to the type-level `F` map. Duplicate flag names
976
+ * are prevented at the type level via the `Exclude` constraint.
977
+ *
978
+ * The builder controls the flag's type, presence, aliases, env/config
979
+ * bindings, and description. See {@link FlagBuilder} for available modifiers.
980
+ *
981
+ * @param name - Flag name (used as `--name` on CLI and `flags.*` in handler).
982
+ * @param builder - Configured `FlagBuilder` from `flag.string()`, `flag.boolean()`,
983
+ * `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
984
+ *
985
+ * @example
986
+ * ```ts
987
+ * command('serve')
988
+ * .flag('port', flag.number()
989
+ * .alias('p')
990
+ * .env('PORT')
991
+ * .default(3000)
992
+ * .describe('Port to listen on'))
993
+ * .flag('host', flag.string()
994
+ * .env('HOST')
995
+ * .default('localhost')
996
+ * .describe('Bind address'))
997
+ * .flag('verbose', flag.boolean()
998
+ * .alias('v')
999
+ * .describe('Enable verbose logging'))
1000
+ * .action(({ flags, out }) => {
1001
+ * flags.port; // number
1002
+ * flags.host; // string
1003
+ * flags.verbose; // boolean
1004
+ * out.log(`Listening on ${flags.host}:${flags.port}`);
1005
+ * });
1006
+ *
1007
+ * // $ mycli serve --port 8080 -v
1008
+ * // $ PORT=9090 mycli serve
1009
+ * ```
1010
+ *
1011
+ * @returns The builder (for chaining).
1012
+ */
1013
+ flag<N extends string, B extends FlagBuilder<FlagConfig>>(
1014
+ name: N & Exclude<N, keyof F>,
1015
+ builder: B,
1016
+ ): CommandBuilder<F & Record<N, B>, A, C> {
1017
+ const nextFlags = { ...this.schema.flags, [name]: builder.schema };
1018
+ return new CommandBuilder(
1019
+ { ...this.schema, flags: nextFlags, hasAction: false },
1020
+ // handler is intentionally dropped — adding a flag invalidates
1021
+ // the previous handler's type signature
1022
+ undefined,
1023
+ this._subcommands,
1024
+ this._executionSteps,
1025
+ );
1026
+ }
1027
+
1028
+ // -- Arg accumulation ----------------------------------------------------
1029
+
1030
+ /**
1031
+ * Register a named positional argument on this command.
1032
+ *
1033
+ * Args are ordered by registration — position on the CLI matches the
1034
+ * order of `.arg()` calls. The arg name is added to the type-level `A`
1035
+ * map. Duplicate arg names are prevented at the type level via the
1036
+ * `Exclude` constraint.
1037
+ *
1038
+ * The builder controls the arg's type, presence, env binding, and
1039
+ * description. See {@link ArgBuilder} for available modifiers.
1040
+ *
1041
+ * @param name - Positional arg name (used in help text and `args.*`).
1042
+ * @param builder - Configured `ArgBuilder` from `arg.string()`, `arg.number()`,
1043
+ * or `arg.custom()`.
1044
+ *
1045
+ * @example
1046
+ * ```ts
1047
+ * command('deploy')
1048
+ * // Required string arg — first positional
1049
+ * .arg('target', arg.string()
1050
+ * .env('DEPLOY_TARGET')
1051
+ * .describe('Deploy target'))
1052
+ * // Optional number arg — second positional
1053
+ * .arg('port', arg.number()
1054
+ * .env('PORT')
1055
+ * .default(3000)
1056
+ * .describe('Port number'))
1057
+ * .action(({ args }) => {
1058
+ * args.target; // string
1059
+ * args.port; // number
1060
+ * });
1061
+ *
1062
+ * // Usage: deploy [flags] <target> [port]
1063
+ * // $ mycli deploy production 8080
1064
+ * // $ DEPLOY_TARGET=staging mycli deploy
1065
+ * ```
1066
+ *
1067
+ * @returns The builder (for chaining).
1068
+ */
1069
+ arg<N extends string, B extends ArgBuilder<ArgConfig>>(
1070
+ name: N & Exclude<N, keyof A>,
1071
+ builder: B,
1072
+ ): CommandBuilder<F, A & Record<N, B>, C> {
1073
+ validateArgEntry(name, builder.schema, this.schema.args);
1074
+ const entry: CommandArgEntry = { name, schema: builder.schema };
1075
+ const nextArgs = [...this.schema.args, entry];
1076
+ return new CommandBuilder(
1077
+ { ...this.schema, args: nextArgs, hasAction: false },
1078
+ // handler is intentionally dropped — adding an arg invalidates
1079
+ // the previous handler's type signature
1080
+ undefined,
1081
+ this._subcommands,
1082
+ this._executionSteps,
1083
+ );
1084
+ }
1085
+
1086
+ // -- Subcommand nesting --------------------------------------------------
1087
+
1088
+ /**
1089
+ * Register a nested subcommand on this command.
1090
+ *
1091
+ * The subcommand's builder is stored in `_subcommands` for the CLI layer's
1092
+ * `eraseCommand()` to traverse when building the execution tree. The
1093
+ * subcommand's `CommandSchema` is also appended to `schema.commands` for
1094
+ * help rendering and completion generation.
1095
+ *
1096
+ * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
1097
+ * parent level (same semantics as `CLIBuilder.command()`). The handler is
1098
+ * preserved.
1099
+ *
1100
+ * @example
1101
+ * ```ts
1102
+ * const db = group('db')
1103
+ * .description('Database operations')
1104
+ * .command(migrateCmd)
1105
+ * .command(seedCmd);
1106
+ * ```
1107
+ *
1108
+ * @param sub - Child {@link CommandBuilder} to nest under this command.
1109
+ * @returns The builder (for chaining).
1110
+ */
1111
+ command<
1112
+ F2 extends Record<string, FlagBuilder<FlagConfig>>,
1113
+ A2 extends Record<string, ArgBuilder<ArgConfig>>,
1114
+ C2 extends Record<string, unknown>,
1115
+ >(sub: CommandBuilder<F2, A2, C2>): CommandBuilder<F, A, C> {
1116
+ return new CommandBuilder(
1117
+ {
1118
+ ...this.schema,
1119
+ commands: [...this.schema.commands, sub.schema],
1120
+ },
1121
+ this.handler,
1122
+ [...this._subcommands, eraseBuilder(sub)],
1123
+ this._executionSteps,
1124
+ );
1125
+ }
1126
+
1127
+ // -- Action handler ------------------------------------------------------
1128
+
1129
+ /**
1130
+ * Register the action handler for this command.
1131
+ *
1132
+ * The handler receives fully typed `{ args, flags, ctx, out }` derived
1133
+ * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
1134
+ * definitions.
1135
+ *
1136
+ * May be synchronous or async. Return values are ignored; command handlers
1137
+ * communicate through `out`, thrown errors, and side effects.
1138
+ *
1139
+ * @param handler - Function receiving `ActionParams<F, A, C>`.
1140
+ *
1141
+ * @example
1142
+ * // Minimal
1143
+ * command('greet')
1144
+ * .arg('name', arg.string())
1145
+ * .action(({ args, out }) => {
1146
+ * out.log(`Hello, ${args.name}!`);
1147
+ * });
1148
+ *
1149
+ * @example
1150
+ * // Full params — flags, args, context, output
1151
+ * command('deploy')
1152
+ * .arg('target', arg.string().env('DEPLOY_TARGET'))
1153
+ * .flag('force', flag.boolean().alias('f'))
1154
+ * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
1155
+ * .middleware(auth)
1156
+ * .action(async ({ args, flags, ctx, out }) => {
1157
+ * args.target; // string
1158
+ * flags.force; // boolean
1159
+ * flags.region; // 'us' | 'eu' | 'ap' | undefined
1160
+ * ctx.user; // User (from auth middleware)
1161
+ *
1162
+ * const spinner = out.spinner('Deploying...');
1163
+ * await deploy(args.target, { force: flags.force });
1164
+ * spinner.stop();
1165
+ * out.log('Done');
1166
+ * });
1167
+ *
1168
+ * @returns The builder (for chaining).
1169
+ */
1170
+ action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C> {
1171
+ return new CommandBuilder(
1172
+ { ...this.schema, hasAction: true },
1173
+ handler,
1174
+ this._subcommands,
1175
+ this._executionSteps,
1176
+ );
1177
+ }
1178
+ }
1179
+
1180
+ // --- Factory function
1181
+
1182
+ /**
1183
+ * Create a new command builder.
1184
+ *
1185
+ * @param name - The command name used for dispatch (e.g. `'deploy'`).
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * const greet = command('greet')
1190
+ * .arg('name', arg.string())
1191
+ * .flag('loud', flag.boolean())
1192
+ * .action(({ args, flags, out }) => {
1193
+ * const msg = `Hello, ${args.name}!`;
1194
+ * out.log(flags.loud ? msg.toUpperCase() : msg);
1195
+ * });
1196
+ * ```
1197
+ *
1198
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
1199
+ */
1200
+ function command(name: string): CommandBuilder {
1201
+ return new CommandBuilder({
1202
+ name,
1203
+ description: undefined,
1204
+ aliases: [],
1205
+ hidden: false,
1206
+ examples: [],
1207
+ flags: {},
1208
+ args: [],
1209
+ hasAction: false,
1210
+ interactive: undefined,
1211
+ middleware: [],
1212
+ commands: [],
1213
+ });
1214
+ }
1215
+
1216
+ /**
1217
+ * Create a command builder intended for use as a command group.
1218
+ *
1219
+ * Semantically identical to `command()` — a group is simply a command that
1220
+ * has subcommands registered via `.command()`. The separate factory
1221
+ * communicates intent: groups organise subcommands, leaf commands have actions.
1222
+ *
1223
+ * A group may also have its own `.action()` (e.g. `git remote` lists remotes
1224
+ * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
1225
+ *
1226
+ * @param name - The group name used for dispatch (e.g. `'db'`).
1227
+ *
1228
+ * @example
1229
+ * ```ts
1230
+ * const db = group('db')
1231
+ * .description('Database operations')
1232
+ * .command(migrateCmd)
1233
+ * .command(seedCmd);
1234
+ * ```
1235
+ *
1236
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
1237
+ */
1238
+ function group(name: string): CommandBuilder {
1239
+ return command(name);
1240
+ }
1241
+
1242
+ // --- Exports
1243
+
1244
+ export type {
1245
+ ActionHandler,
1246
+ ActionParams,
1247
+ AnyCommandBuilder,
1248
+ CommandArgEntry,
1249
+ CommandConfig,
1250
+ CommandExample,
1251
+ CommandMeta,
1252
+ CommandSchema,
1253
+ DeriveHandler,
1254
+ DeriveParams,
1255
+ ErasedCommand,
1256
+ ErasedDeriveHandler,
1257
+ ErasedInteractiveResolver,
1258
+ InteractiveParams,
1259
+ InteractiveResolver,
1260
+ InteractiveResult,
1261
+ Out,
1262
+ };
1263
+ export { CommandBuilder, command, group };