@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3

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