@kjanat/dreamcli 1.0.0 → 2.0.1

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 (217) hide show
  1. package/CHANGELOG.md +63 -6
  2. package/LICENSE +1 -1
  3. package/README.md +296 -164
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -920
  96. package/dist/index.mjs +1 -10
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +6 -252
  115. package/dist/runtime.mjs +1 -1
  116. package/dist/testkit.d.mts +5 -24
  117. package/dist/testkit.mjs +1 -1
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +2 -2
  122. package/examples/gh/package.json +7 -11
  123. package/examples/gh/src/commands/auth.ts +2 -2
  124. package/examples/gh/src/commands/issue.ts +4 -4
  125. package/examples/gh/src/commands/pr.ts +4 -4
  126. package/examples/gh/src/docs.ts +11 -0
  127. package/examples/gh/src/lib/auth.ts +1 -1
  128. package/examples/gh/src/main.test.ts +6 -5
  129. package/examples/gh/src/main.ts +8 -6
  130. package/examples/interactive.ts +3 -3
  131. package/examples/json-mode.ts +4 -6
  132. package/examples/middleware.ts +3 -3
  133. package/examples/multi-command.ts +3 -3
  134. package/examples/spinner-progress.ts +5 -5
  135. package/examples/testing.ts +8 -6
  136. package/package.json +70 -44
  137. package/src/core/cli/dispatch.ts +4 -0
  138. package/src/core/cli/index.ts +185 -632
  139. package/src/core/cli/planner.ts +413 -0
  140. package/src/core/cli/plugin.ts +7 -1
  141. package/src/core/cli/propagate.ts +1 -1
  142. package/src/core/cli/runtime-preflight.ts +409 -0
  143. package/src/core/completion/index.ts +15 -9
  144. package/src/core/completion/shells/bash.ts +6 -3
  145. package/src/core/completion/shells/fish.ts +245 -10
  146. package/src/core/completion/shells/powershell.ts +390 -9
  147. package/src/core/completion/shells/shared.ts +4 -4
  148. package/src/core/completion/shells/zsh.ts +12 -7
  149. package/src/core/config/index.ts +7 -4
  150. package/src/core/config/package-json.ts +6 -2
  151. package/src/core/errors/index.ts +23 -8
  152. package/src/core/execution/index.ts +270 -0
  153. package/src/core/help/index.ts +13 -15
  154. package/src/core/json-schema/index.ts +193 -7
  155. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  156. package/src/core/output/contracts.ts +194 -0
  157. package/src/core/output/index.ts +47 -82
  158. package/src/core/output/renderers.ts +125 -0
  159. package/src/core/parse/index.ts +39 -21
  160. package/src/core/prompt/index.ts +44 -27
  161. package/src/core/resolve/args.ts +144 -0
  162. package/src/core/resolve/coerce.ts +432 -0
  163. package/src/core/resolve/config.ts +26 -0
  164. package/src/core/resolve/contracts.ts +135 -0
  165. package/src/core/resolve/errors.ts +227 -0
  166. package/src/core/resolve/flags.ts +205 -0
  167. package/src/core/resolve/index.ts +41 -1264
  168. package/src/core/resolve/property.ts +99 -0
  169. package/src/core/schema/activity.ts +3 -0
  170. package/src/core/schema/arg.ts +26 -14
  171. package/src/core/schema/command.ts +265 -38
  172. package/src/core/schema/flag.ts +120 -15
  173. package/src/core/schema/index.ts +11 -2
  174. package/src/core/schema/middleware.ts +6 -6
  175. package/src/core/schema/prompt.ts +9 -1
  176. package/src/core/schema/run.ts +25 -17
  177. package/src/core/schema-dsl/index.ts +109 -0
  178. package/src/core/schema-dsl/parse.ts +262 -0
  179. package/src/core/schema-dsl/runtime.ts +609 -0
  180. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  181. package/src/core/testkit/index.ts +55 -297
  182. package/src/index.ts +10 -4
  183. package/src/runtime/adapter.ts +13 -10
  184. package/src/runtime/auto.ts +3 -3
  185. package/src/runtime/bun.ts +4 -4
  186. package/src/runtime/deno.ts +43 -29
  187. package/src/runtime/detect.ts +4 -1
  188. package/src/runtime/index.ts +1 -1
  189. package/src/runtime/node.ts +43 -21
  190. package/src/runtime/paths.ts +9 -3
  191. package/src/runtime/support.ts +20 -4
  192. package/src/runtime.ts +1 -1
  193. package/src/testkit.ts +10 -8
  194. package/dist/adapter-CCSh5juX.cjs +0 -1
  195. package/dist/adapter-DIwO-q7K.d.mts +0 -3447
  196. package/dist/adapter-DQnxxLiE.d.cts +0 -3447
  197. package/dist/auto-5cjZaF9V.mjs +0 -3
  198. package/dist/auto-B0eSgoDw.cjs +0 -3
  199. package/dist/index.cjs +0 -10
  200. package/dist/index.d.cts +0 -920
  201. package/dist/runtime.cjs +0 -1
  202. package/dist/runtime.d.cts +0 -253
  203. package/dist/testkit-CEDYPvhF.mjs +0 -14
  204. package/dist/testkit-ClIKijxC.cjs +0 -14
  205. package/dist/testkit.cjs +0 -1
  206. package/dist/testkit.d.cts +0 -25
  207. package/examples/gh/tsconfig.json +0 -37
  208. package/examples/tsconfig.json +0 -17
  209. package/src/core/cli/AGENTS.md +0 -72
  210. package/src/core/completion/AGENTS.md +0 -72
  211. package/src/core/completion/completion-test-helpers.ts +0 -48
  212. package/src/core/output/AGENTS.md +0 -69
  213. package/src/core/resolve/AGENTS.md +0 -69
  214. package/src/core/schema/AGENTS.md +0 -61
  215. package/src/core/testkit/AGENTS.md +0 -55
  216. package/src/runtime/AGENTS.md +0 -74
  217. package/src/runtime/test-helpers.ts +0 -40
@@ -0,0 +1,960 @@
1
+ import { ProgressHandle, ProgressOptions, SpinnerHandle, SpinnerOptions, TableColumn, TableOptions } from "./activity.mjs";
2
+ import { ArgBuilder, ArgConfig, ArgSchema, InferArgs } from "./arg.mjs";
3
+ import { PromptConfig } from "./prompt.mjs";
4
+ import { FlagBuilder, FlagConfig, FlagSchema, InferFlags } from "./flag.mjs";
5
+ import { ErasedMiddlewareHandler, Middleware } from "./middleware.mjs";
6
+ import { RunOptions, RunResult } from "./run.mjs";
7
+
8
+ //#region src/core/schema/command.d.ts
9
+ /**
10
+ * Widen the context type when adding middleware.
11
+ *
12
+ * The default `C = Record<string, never>` uses an index signature where
13
+ * every key maps to `never` — making property access a type error until
14
+ * middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
15
+ * collapses all properties to `never` because `never & T = never`.
16
+ *
17
+ * This utility replaces `Record<string, never>` entirely on the first
18
+ * `.middleware()` call. Subsequent calls use plain intersection.
19
+ */
20
+ type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
21
+ /**
22
+ * Widen the context type when adding command-scoped derived context.
23
+ *
24
+ * Validation-only derive handlers return `undefined`, preserving `C`.
25
+ * Context-producing derive handlers return an object that merges into `C`
26
+ * using the same first-call replacement rules as middleware.
27
+ */
28
+ type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
29
+ /**
30
+ * Compile-time state carried through the command builder chain.
31
+ *
32
+ * `F` accumulates named flag builders; `A` accumulates named arg builders.
33
+ * Both start empty (`{}`) and grow as `.flag()` / `.arg()` are called.
34
+ */
35
+ interface CommandConfig {
36
+ /** Accumulated flag builders keyed by flag name. */
37
+ readonly flags: Record<string, FlagBuilder<FlagConfig>>;
38
+ /** Accumulated arg builders keyed by arg name. */
39
+ readonly args: Record<string, ArgBuilder<ArgConfig>>;
40
+ }
41
+ /**
42
+ * Parameters received by the interactive resolver function.
43
+ *
44
+ * `flags` contains partially resolved values — present for flags resolved
45
+ * via CLI, env, or config, `undefined` for unresolved flags. The resolver
46
+ * uses this to decide which prompts to show based on current state.
47
+ */
48
+ interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
49
+ /** Partially resolved flag values (after CLI/env/config, before prompts). */
50
+ readonly flags: Readonly<Partial<InferFlags<F>>>;
51
+ }
52
+ /**
53
+ * A record mapping flag names to prompt configs or falsy values.
54
+ *
55
+ * - `PromptConfig` — show this prompt for the flag
56
+ * - `false | undefined | null | 0 | ''` — skip prompting for this flag
57
+ *
58
+ * Only flag names that need prompting should have truthy values.
59
+ * Flags not mentioned are handled by their per-flag `.prompt()` config.
60
+ */
61
+ type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
62
+ /**
63
+ * Interactive resolver function for command-level prompt control.
64
+ *
65
+ * Called after CLI/env/config resolution but before per-flag prompts fire.
66
+ * Receives partially resolved values and returns a prompt schema for
67
+ * flags that should be prompted. Commands without `.interactive()` use
68
+ * per-flag prompt configs directly.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * import { command, flag } from '@kjanat/dreamcli';
73
+ *
74
+ * const deploy = command('deploy')
75
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
76
+ * .interactive(({ flags }) => ({
77
+ * region: !flags.region && {
78
+ * kind: 'select',
79
+ * message: 'Select region',
80
+ * },
81
+ * }))
82
+ * .action(({ flags, out }) => {
83
+ * out.log(`Deploying to ${flags.region}`);
84
+ * });
85
+ * ```
86
+ */
87
+ type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (params: InteractiveParams<F>) => InteractiveResult;
88
+ /**
89
+ * Type-erased interactive resolver stored on {@linkcode CommandSchema}.
90
+ *
91
+ * Advanced bridge type: most consumers should use {@link InteractiveResolver}
92
+ * via {@linkcode command | command().interactive()} and never reference this alias directly.
93
+ *
94
+ * At runtime, the resolver receives `{ flags: Record<string, unknown> }`
95
+ * and returns `Record<string, PromptConfig | falsy>`. The phantom types
96
+ * from `CommandBuilder<F, A>` are erased.
97
+ *
98
+ * @internal
99
+ */
100
+ type ErasedInteractiveResolver = (params: {
101
+ readonly flags: Readonly<Record<string, unknown>>;
102
+ }) => InteractiveResult;
103
+ /**
104
+ * Output channel available inside action handlers.
105
+ *
106
+ * Provides structured methods for stdout/stderr, JSON output,
107
+ * spinners, progress bars, and tables. The real implementation lives in
108
+ * `src/core/output/`; this interface defines the shape that handlers consume.
109
+ */
110
+ interface Out {
111
+ /** Write to stdout (normal output). */
112
+ log(message: string): void;
113
+ /** Informational (may be suppressed in quiet mode). */
114
+ info(message: string): void;
115
+ /** Warning to stderr. */
116
+ warn(message: string): void;
117
+ /** Error to stderr. */
118
+ error(message: string): void;
119
+ /**
120
+ * Emit a structured JSON value to stdout.
121
+ *
122
+ * Always serialises `value` as JSON to stdout regardless of output
123
+ * mode. Prefer this over `log(JSON.stringify(...))` so the output
124
+ * channel can enforce consistent formatting and future features
125
+ * (pretty-print in TTY, streaming JSON, etc.).
126
+ */
127
+ json(value: unknown): void;
128
+ /**
129
+ * Whether the output channel is in JSON mode (`--json` flag active).
130
+ *
131
+ * Handlers can check this to skip decorative output (spinners,
132
+ * progress bars, ANSI formatting) when machine-readable output is
133
+ * expected.
134
+ */
135
+ readonly jsonMode: boolean;
136
+ /**
137
+ * Whether stdout is connected to a TTY (terminal).
138
+ *
139
+ * Handlers can check this to decide whether to emit decorative output
140
+ * (spinners, progress bars, ANSI color codes). When `false`, the output
141
+ * is being piped or redirected — skip interactive decorations.
142
+ *
143
+ * Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
144
+ * decorative output should be suppressed regardless of `isTTY`.
145
+ */
146
+ readonly isTTY: boolean;
147
+ /**
148
+ * Render tabular data.
149
+ *
150
+ * - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
151
+ * - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
152
+ * - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
153
+ * (useful for `grep`, `awk`, etc.).
154
+ * - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
155
+ * side channel while `json()` writes machine output to stdout.
156
+ *
157
+ * When `columns` is omitted, columns are auto-inferred from the keys
158
+ * of the first row. Column headers default to the key name.
159
+ *
160
+ * When `columns` is provided, both text and JSON output are projected to
161
+ * only the listed keys.
162
+ *
163
+ * @param rows - Array of row objects.
164
+ */
165
+ table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
166
+ /**
167
+ * Render tabular data with explicit column selection.
168
+ *
169
+ * @param rows - Array of row objects.
170
+ * @param columns - Column descriptors controlling which keys are shown and header labels.
171
+ * @param options - Per-call rendering options (format, stream).
172
+ */
173
+ table<T extends Record<string, unknown>>(rows: readonly T[], columns?: readonly TableColumn<T>[], options?: TableOptions): void;
174
+ /**
175
+ * Create a spinner for indeterminate progress feedback.
176
+ *
177
+ * Returns a handle for lifecycle control. In non-TTY/jsonMode,
178
+ * returns a no-op handle (or static fallback if configured).
179
+ *
180
+ * @param text - Initial spinner text.
181
+ * @param options - Fallback strategy for non-TTY environments.
182
+ * @returns A {@link SpinnerHandle} for lifecycle control.
183
+ */
184
+ spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
185
+ /**
186
+ * Create a progress bar for measured work.
187
+ *
188
+ * Returns a handle for updating progress. Pass `total` for
189
+ * determinate mode (percentage bar); omit for indeterminate (pulsing).
190
+ *
191
+ * @param options - Progress configuration (total, label, fallback).
192
+ * @returns A {@link ProgressHandle} for updating progress.
193
+ */
194
+ progress(options: ProgressOptions): ProgressHandle;
195
+ /**
196
+ * Stop the currently active spinner or progress handle, if any.
197
+ *
198
+ * TTY spinner and progress handles start `setInterval` timers that
199
+ * prevent the process from exiting until a terminal method (`stop`,
200
+ * `succeed`, `fail`, `done`) is called. If a handler throws before
201
+ * reaching that call, the timer leaks and the process hangs.
202
+ *
203
+ * Call `stopActive()` in a `finally` block after handler execution
204
+ * to guarantee cleanup. It is idempotent — safe to call when no
205
+ * handle is active, or when the handle was already stopped.
206
+ *
207
+ * The framework calls this automatically in `runCommand()` and
208
+ * `cli().run()`. Direct users of `createOutput()` should call it
209
+ * themselves after the handler returns or throws.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * const out = createOutput({ isTTY: true });
214
+ * try {
215
+ * await handler({ out });
216
+ * } finally {
217
+ * out.stopActive();
218
+ * }
219
+ * ```
220
+ */
221
+ stopActive(): void;
222
+ }
223
+ /**
224
+ * Runtime metadata about the CLI program and current command execution.
225
+ *
226
+ * Available to action handlers and middleware.
227
+ *
228
+ * Populated by the CLI dispatch layer from {@link CLISchema} and
229
+ * {@link CommandSchema}. For standalone `runCommand()` calls without
230
+ * a CLI wrapper, a minimal meta is constructed from the command's own schema.
231
+ */
232
+ interface CommandMeta {
233
+ /** CLI program name (from `cli('name')` or package.json inference). */
234
+ readonly name: string;
235
+ /** Binary display name used in help/usage (may differ from `name`). */
236
+ readonly bin: string;
237
+ /** Program version, if set via `.version()` or discovered from package.json. */
238
+ readonly version: string | undefined;
239
+ /** The leaf command name currently being executed. */
240
+ readonly command: string;
241
+ }
242
+ /**
243
+ * The bag of values received by an action handler.
244
+ *
245
+ * - `args` — fully resolved positional arguments
246
+ * - `flags` — fully resolved flags
247
+ * - `ctx` — derive/middleware-provided context
248
+ * - `out` — output channel
249
+ * - `meta` — CLI program metadata (name, bin, version, command)
250
+ *
251
+ * The `C` parameter defaults to `Record<string, never>`, making `ctx`
252
+ * property access a type error until derive or middleware extends it.
253
+ */
254
+ interface ActionParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> {
255
+ /** Fully resolved positional argument values, typed from `.arg()` definitions. */
256
+ readonly args: Readonly<InferArgs<A>>;
257
+ /** Fully resolved flag values, typed from `.flag()` definitions. */
258
+ readonly flags: Readonly<InferFlags<F>>;
259
+ /** Middleware/derive-provided context, typed from `.middleware()` and `.derive()` chains. */
260
+ readonly ctx: Readonly<C>;
261
+ /** Structured output channel for stdout, stderr, JSON, tables, and spinners. */
262
+ readonly out: Out;
263
+ /** Runtime metadata about the CLI program and current command. */
264
+ readonly meta: CommandMeta;
265
+ }
266
+ /**
267
+ * Action handler function signature.
268
+ *
269
+ * May be sync or async — the framework will `await` the return value
270
+ * regardless. The `C` parameter carries the accumulated middleware
271
+ * context type (defaults to empty).
272
+ */
273
+ type ActionHandler<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> = (params: ActionParams<F, A, C>) => void | Promise<void>;
274
+ /**
275
+ * Type-erased action handler stored on {@linkcode CommandBuilder}.
276
+ *
277
+ * The typed {@linkcode ActionHandler} from `.action()` is cast to this
278
+ * erased form at the type-erasure boundary, keeping {@linkcode CommandBuilder}
279
+ * covariant in its generic parameters. This enables structural
280
+ * compatibility across TypeScript declaration-file boundaries where
281
+ * generic inference may fall back to constraint types.
282
+ *
283
+ * Follows the same erasure pattern as {@link ErasedDeriveHandler} and
284
+ * {@link ErasedMiddlewareHandler}.
285
+ *
286
+ * @internal
287
+ */
288
+ type ErasedActionHandler = (params: {
289
+ readonly args: Readonly<Record<string, unknown>>;
290
+ readonly flags: Readonly<Record<string, unknown>>;
291
+ readonly ctx: Readonly<Record<string, unknown>>;
292
+ readonly out: Out;
293
+ readonly meta: CommandMeta;
294
+ }) => void | Promise<void>;
295
+ /**
296
+ * The bag of values received by a derive handler.
297
+ *
298
+ * Identical to {@link ActionParams}: derives run after full resolution and
299
+ * before the action handler, with typed args/flags/current context plus `out`
300
+ * and `meta`.
301
+ */
302
+ type DeriveParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> = ActionParams<F, A, C>;
303
+ /**
304
+ * Command-scoped typed pre-action handler.
305
+ *
306
+ * Derive handlers may:
307
+ * - validate resolved input and throw {@linkcode CLIError}
308
+ * - return `undefined` to continue without changing context
309
+ * - return an object whose properties merge into `ctx` downstream
310
+ *
311
+ * They cannot wrap downstream execution; use {@linkcode middleware} for that.
312
+ */
313
+ type DeriveHandler<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>, Output extends Record<string, unknown> | undefined = undefined> = (params: DeriveParams<F, A, C>) => Output | Promise<Output>;
314
+ /**
315
+ * Type-erased derive handler stored on the command builder.
316
+ *
317
+ * @internal
318
+ */
319
+ type ErasedDeriveHandler = (params: {
320
+ readonly args: Readonly<Record<string, unknown>>;
321
+ readonly flags: Readonly<Record<string, unknown>>;
322
+ readonly ctx: Readonly<Record<string, unknown>>;
323
+ readonly out: Out;
324
+ readonly meta: CommandMeta;
325
+ }) => undefined | Readonly<Record<string, unknown>> | Promise<undefined | Readonly<Record<string, unknown>>>;
326
+ /**
327
+ * Internal execution step union preserving registration order across
328
+ * {@linkcode CommandBuilder.derive | derive()} and {@linkcode CommandBuilder.middleware | middleware()}.
329
+ *
330
+ * @internal
331
+ */
332
+ type ExecutionStep = {
333
+ readonly kind: 'derive';
334
+ readonly handler: ErasedDeriveHandler;
335
+ } | {
336
+ readonly kind: 'middleware';
337
+ readonly handler: ErasedMiddlewareHandler;
338
+ };
339
+ /** A single usage example shown in help text. */
340
+ interface CommandExample {
341
+ /** The command invocation (e.g. `'deploy production --force'`). */
342
+ readonly command: string;
343
+ /** Optional description of what this example does. */
344
+ readonly description?: string;
345
+ }
346
+ /**
347
+ * Runtime descriptor produced by {@link CommandBuilder}.
348
+ *
349
+ * Consumers (parser, help generator, CLI dispatcher) read this to
350
+ * understand the command's shape — flags, args, aliases, subcommands,
351
+ * middleware, and interactive resolver.
352
+ */
353
+ interface CommandSchema {
354
+ /** The command name (used for dispatch, e.g. `'deploy'`). */
355
+ readonly name: string;
356
+ /** Human-readable description for help text. */
357
+ readonly description: string | undefined;
358
+ /** Alternative names for this command. */
359
+ readonly aliases: readonly string[];
360
+ /** Whether this command is hidden from help listings. */
361
+ readonly hidden: boolean;
362
+ /** Usage examples for help text. */
363
+ readonly examples: readonly CommandExample[];
364
+ /** Named flag schemas, keyed by flag name. */
365
+ readonly flags: Readonly<Record<string, FlagSchema>>;
366
+ /** Ordered positional arg entries (name + schema). */
367
+ readonly args: readonly CommandArgEntry[];
368
+ /** Whether an action handler has been registered. */
369
+ readonly hasAction: boolean;
370
+ /**
371
+ * Command-level interactive resolver for schema-driven prompt control.
372
+ *
373
+ * When set, called after CLI/env/config resolution with partially resolved
374
+ * flag values. Returns prompt configs for flags that need interactive input.
375
+ * Takes precedence over per-flag `.prompt()` configs for flags it returns
376
+ * configs for; flags not mentioned fall back to their per-flag configs.
377
+ *
378
+ * @see InteractiveResolver
379
+ */
380
+ readonly interactive: ErasedInteractiveResolver | undefined;
381
+ /**
382
+ * Middleware handlers to run before the action handler.
383
+ *
384
+ * Executed in registration order — first middleware registered runs
385
+ * first and calls `next()` to proceed to subsequent middleware,
386
+ * ending with the action handler. Context accumulates via intersection
387
+ * at the type level and via object spread at runtime.
388
+ */
389
+ readonly middleware: readonly ErasedMiddlewareHandler[];
390
+ /**
391
+ * Nested subcommand schemas (for help rendering and completion).
392
+ *
393
+ * Pure data — no execution closures. Populated by `.command()` on
394
+ * `CommandBuilder`. Empty for leaf commands.
395
+ */
396
+ readonly commands: readonly CommandSchema[];
397
+ }
398
+ /**
399
+ * A named positional argument entry in the command schema.
400
+ *
401
+ * Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
402
+ * The array ordering in {@link CommandSchema.args} determines CLI position.
403
+ */
404
+ interface CommandArgEntry {
405
+ /** User-facing argument name (shown in help as `<name>`). */
406
+ readonly name: string;
407
+ /** Runtime descriptor controlling parsing, presence, and coercion. */
408
+ readonly schema: ArgSchema;
409
+ }
410
+ /**
411
+ * A type-erased command entry for heterogeneous command storage.
412
+ *
413
+ * Advanced/internal bridge type: most consumers should work with
414
+ * {@link CommandBuilder} and never reference `ErasedCommand` directly.
415
+ *
416
+ * Commands registered via `CLIBuilder.command()` have heterogeneous `F`, `A`,
417
+ * and `C` type parameters. At the dispatch level we only need the runtime
418
+ * schema (for name/alias matching and help) and the ability to delegate to
419
+ * `runCommand()`. This interface captures exactly that contract.
420
+ *
421
+ * The `_execute` function closes over the original typed {@linkcode CommandBuilder},
422
+ * preserving full type safety inside the closure while presenting a
423
+ * uniform interface to the dispatcher.
424
+ *
425
+ * Defined here (rather than in the CLI layer) so both {@linkcode CommandBuilder} and
426
+ * `CLIBuilder` can reference it without circular imports.
427
+ *
428
+ * @internal
429
+ */
430
+ interface ErasedCommand {
431
+ /** Runtime schema for name matching and help rendering. */
432
+ readonly schema: CommandSchema;
433
+ /**
434
+ * Nested subcommands (name/alias → erased child).
435
+ *
436
+ * Built recursively by `eraseCommand()` in the CLI layer.
437
+ * Empty map for leaf commands. The dispatch layer uses this for
438
+ * recursive command tree traversal.
439
+ *
440
+ * @internal
441
+ */
442
+ readonly subcommands: ReadonlyMap<string, ErasedCommand>;
443
+ /** Original command builder captured at the type-erasure boundary. */
444
+ readonly _command?: AnyCommandBuilder;
445
+ /** Execute this command against argv. Closes over the typed CommandBuilder. */
446
+ readonly _execute: (argv: readonly string[], options?: RunOptions) => Promise<RunResult>;
447
+ }
448
+ /**
449
+ * Structural subset of {@linkcode CommandBuilder} consumed by the execution pipeline.
450
+ *
451
+ * Avoids generic type parameters so any `CommandBuilder<F, A, C>` satisfies
452
+ * this interface structurally — no variance constraints, no inference needed.
453
+ * Used by `runCommand()` and the shared executor to accept commands without
454
+ * requiring TypeScript to resolve {@linkcode CommandBuilder}'s full generic signature.
455
+ *
456
+ * @internal
457
+ */
458
+ interface RunnableCommand {
459
+ readonly schema: CommandSchema;
460
+ readonly handler: ErasedActionHandler | undefined;
461
+ readonly _executionSteps: readonly ExecutionStep[];
462
+ }
463
+ /**
464
+ * Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
465
+ *
466
+ * Advanced helper alias: useful only when working on DreamCLI internals or
467
+ * custom tooling that mirrors the framework's type-erasure boundary.
468
+ *
469
+ * Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
470
+ * assignable. The CLI layer's `eraseCommand()` traverses these to build
471
+ * the execution tree.
472
+ *
473
+ * @internal
474
+ */
475
+ type AnyCommandBuilder = CommandBuilder<Record<string, FlagBuilder<FlagConfig>>, Record<string, ArgBuilder<ArgConfig>>, Record<string, unknown>>;
476
+ /**
477
+ * Immutable command schema builder.
478
+ *
479
+ * The type parameters `F` (flags), `A` (args), and `C` (context) are
480
+ * phantom types that accumulate builder types as `.flag()`, `.arg()`,
481
+ * `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
482
+ * fully typed `ActionParams<F, A, C>`.
483
+ *
484
+ * `C` defaults to `Record<string, never>`, making `ctx` property
485
+ * access a type error until derive or middleware extends it.
486
+ *
487
+ * @example
488
+ * ```ts
489
+ * const deploy = command('deploy')
490
+ * .description('Deploy to an environment')
491
+ * .arg('target', arg.string().describe('Deploy target'))
492
+ * .flag('force', flag.boolean().alias('f'))
493
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
494
+ * .action(async ({ args, flags, out }) => {
495
+ * // args.target: string
496
+ * // flags.force: boolean
497
+ * // flags.region: 'us' | 'eu' | 'ap' | undefined
498
+ * out.log(`Deploying ${args.target}...`);
499
+ * });
500
+ * ```
501
+ */
502
+ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> = {}, A extends Record<string, ArgBuilder<ArgConfig>> = {}, C extends Record<string, unknown> = Record<string, never>> {
503
+ /** @internal Runtime schema descriptor. */
504
+ readonly schema: CommandSchema;
505
+ /** @internal The action handler, if registered (type-erased for covariance). */
506
+ readonly handler: ErasedActionHandler | undefined;
507
+ /**
508
+ * @internal Nested sub-command builders (type-erased for heterogeneous storage).
509
+ *
510
+ * Stored separately from `schema.commands` because builders carry action
511
+ * handlers and phantom types needed by `eraseCommand()` in the CLI layer.
512
+ * `schema.commands` holds pure `CommandSchema[]` for help/completion.
513
+ */
514
+ readonly _subcommands: readonly AnyCommandBuilder[];
515
+ /**
516
+ * @internal Execution steps in registration order.
517
+ *
518
+ * Distinct from `schema.middleware`: middleware handlers remain in schema
519
+ * for backward compatibility, while derives stay command-local and builder-
520
+ * scoped so future shared/global middleware can compose cleanly.
521
+ */
522
+ readonly _executionSteps: readonly ExecutionStep[];
523
+ /** @internal Phantom brand for accumulated flag builder types. No runtime value. */
524
+ readonly _flags: F;
525
+ /** @internal Phantom brand for accumulated arg builder types. No runtime value. */
526
+ readonly _args: A;
527
+ /** @internal Phantom brand for accumulated context type. No runtime value. */
528
+ readonly _ctx: C;
529
+ /**
530
+ * Create a command builder from a pre-built schema descriptor.
531
+ *
532
+ * @param schema - Runtime command descriptor.
533
+ * @param handler - Action handler, if registered.
534
+ * @param subcommands - Nested sub-command builders (type-erased).
535
+ * @param executionSteps - Derive/middleware steps in registration order.
536
+ */
537
+ constructor(schema: CommandSchema, handler?: ErasedActionHandler, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);
538
+ /**
539
+ * Register a command-level interactive resolver for schema-driven prompts.
540
+ *
541
+ * The resolver is called after CLI/env/config resolution with partially
542
+ * resolved flag values. It returns a prompt schema for flags that need
543
+ * interactive input based on the current state.
544
+ *
545
+ * For flags the resolver returns a {@linkcode PromptConfig}, that config is used
546
+ * instead of any per-flag `.prompt()` config. For flags returned as falsy
547
+ * (or not mentioned), per-flag `.prompt()` configs are used as fallback.
548
+ *
549
+ * Commands without `.interactive()` use per-flag prompt configs directly.
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * const deploy = command('deploy')
554
+ * .flag('region', flag.enum(['us', 'eu', 'ap']))
555
+ * .flag('force', flag.boolean())
556
+ * .interactive(({ flags }) => ({
557
+ * region: !flags.region && {
558
+ * kind: 'select',
559
+ * message: 'Select region',
560
+ * },
561
+ * }))
562
+ * .action(({ flags }) => { ... });
563
+ * ```
564
+ *
565
+ * @param resolver - Function receiving partially resolved flags and returning prompt configs.
566
+ * @returns The builder (for chaining).
567
+ */
568
+ interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;
569
+ /**
570
+ * Register a command-scoped typed pre-action handler.
571
+ *
572
+ * Derive runs after full resolution and before the action handler.
573
+ * It receives typed `{ args, flags, ctx, out, meta }` and may either:
574
+ *
575
+ * - return `undefined` for validation-only behavior
576
+ * - return an object to merge additional properties into `ctx`
577
+ *
578
+ * Unlike middleware, derive cannot wrap downstream execution and does not
579
+ * use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
580
+ * or error-boundary patterns.
581
+ *
582
+ * Adding derive drops the current handler (like `.flag()`, `.arg()`, and
583
+ * `.middleware()`) because the action handler's `ctx` type may change.
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * command('deploy')
588
+ * .flag('token', flag.string().env('AUTH_TOKEN'))
589
+ * .derive(({ flags }) => {
590
+ * if (!flags.token) {
591
+ * throw new CLIError('Not authenticated', {
592
+ * code: 'AUTH_REQUIRED',
593
+ * suggest: 'Run `mycli login` or set AUTH_TOKEN',
594
+ * });
595
+ * }
596
+ * return { token: flags.token };
597
+ * })
598
+ * .action(({ ctx }) => {
599
+ * ctx.token; // string
600
+ * });
601
+ * ```
602
+ *
603
+ * @param handler - Derive function receiving typed args/flags/ctx.
604
+ * @returns The builder (for chaining).
605
+ */
606
+ derive<Output extends Record<string, unknown> | undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;
607
+ /**
608
+ * Register middleware to run before the action handler.
609
+ *
610
+ * Middleware executes in registration order. Each middleware receives
611
+ * `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
612
+ * to continue the chain. Context additions are merged and become
613
+ * typed downstream.
614
+ *
615
+ * Adding middleware widens `C` via intersection and drops the current
616
+ * handler (like `.flag()` / `.arg()` — the handler's type signature
617
+ * changes when context changes).
618
+ *
619
+ * @example
620
+ * ```ts
621
+ * import { CLIError, command, middleware } from '@kjanat/dreamcli';
622
+ *
623
+ * interface User {
624
+ * id: string;
625
+ * email: string;
626
+ * }
627
+ *
628
+ * async function getCurrentUser(): Promise<User | null> {
629
+ * return { id: 'u_123', email: 'dev@example.com' };
630
+ * }
631
+ *
632
+ * function startTrace(name: string): string {
633
+ * return `trace:${name}`;
634
+ * }
635
+ *
636
+ * // Resolve the current user and expose it as `ctx.user` downstream.
637
+ * const auth = middleware<{ user: User }>(async ({ next }) => {
638
+ * const user = await getCurrentUser();
639
+ * if (!user) {
640
+ * throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
641
+ * }
642
+ * await next({ user });
643
+ * });
644
+ *
645
+ * // Create a trace id for this command run and expose it as `ctx.traceId`.
646
+ * const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
647
+ * const traceId = startTrace(`${meta.name}.${meta.command}`);
648
+ * await next({ traceId });
649
+ * });
650
+ *
651
+ * command('deploy')
652
+ * .middleware(auth) // C becomes { user: User }
653
+ * .middleware(telemetry) // C becomes { user: User } & { traceId: string }
654
+ * .action(({ ctx }) => {
655
+ * ctx.user; // User — typed
656
+ * ctx.traceId; // string — typed
657
+ * });
658
+ * ```
659
+ *
660
+ * @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
661
+ * Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
662
+ * @returns The builder (for chaining).
663
+ */
664
+ middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;
665
+ /**
666
+ * Set the command's description for help text.
667
+ *
668
+ * Displayed below the usage line in `--help` output and next to the
669
+ * command name in parent command/group help listings.
670
+ *
671
+ * @param text - One-line description of what the command does.
672
+ *
673
+ * @example
674
+ * ```ts
675
+ * command('deploy')
676
+ * .description('Deploy the application to a target environment')
677
+ * .action(({ out }) => { out.log('deploying...'); });
678
+ *
679
+ * // $ mycli deploy --help
680
+ * // Usage: deploy [flags]
681
+ * //
682
+ * // Deploy the application to a target environment
683
+ * ```
684
+ *
685
+ * @returns The builder (for chaining).
686
+ */
687
+ description(text: string): CommandBuilder<F, A, C>;
688
+ /**
689
+ * Add an alternative name for this command.
690
+ *
691
+ * Aliases are accepted during dispatch alongside the primary name.
692
+ * Multiple aliases can be chained. Aliases are shown in help output.
693
+ *
694
+ * @param name - Alternative command name (e.g. `'d'` for `deploy`).
695
+ *
696
+ * @example
697
+ * ```ts
698
+ * command('deploy')
699
+ * .alias('d')
700
+ * .alias('push')
701
+ * .action(({ out }) => { out.log('deploying...'); });
702
+ *
703
+ * // All equivalent:
704
+ * // $ mycli deploy
705
+ * // $ mycli d
706
+ * // $ mycli push
707
+ * ```
708
+ *
709
+ * @returns The builder (for chaining).
710
+ */
711
+ alias(name: string): CommandBuilder<F, A, C>;
712
+ /**
713
+ * Hide this command from help listings.
714
+ *
715
+ * The command remains fully functional and dispatchable — it just
716
+ * won't appear in `--help` output or shell completions. Useful for
717
+ * internal/debug commands.
718
+ *
719
+ * @example
720
+ * ```ts
721
+ * command('debug-dump')
722
+ * .hidden()
723
+ * .action(({ out }) => { out.log(JSON.stringify(internalState)); });
724
+ *
725
+ * // $ mycli --help → 'debug-dump' is not listed
726
+ * // $ mycli debug-dump → still works
727
+ * ```
728
+ *
729
+ * @returns The builder (for chaining).
730
+ */
731
+ hidden(): CommandBuilder<F, A, C>;
732
+ /**
733
+ * Add a usage example to help text.
734
+ *
735
+ * Examples are rendered in the "Examples:" section of `--help` output.
736
+ * Call multiple times to add several examples. Each example shows a
737
+ * shell invocation, optionally with a description.
738
+ *
739
+ * @param cmd - The example command line (without the program name prefix).
740
+ * @param description - Optional one-line explanation of what the example does.
741
+ *
742
+ * @example
743
+ * ```ts
744
+ * command('deploy')
745
+ * .arg('target', arg.string())
746
+ * .flag('force', flag.boolean().alias('f'))
747
+ * .example('deploy production', 'Deploy to production')
748
+ * .example('deploy staging -f', 'Force deploy to staging')
749
+ * .action(({ args, flags }) => { ... });
750
+ *
751
+ * // $ mycli deploy --help
752
+ * // ...
753
+ * // Examples:
754
+ * // deploy production Deploy to production
755
+ * // deploy staging -f Force deploy to staging
756
+ * ```
757
+ *
758
+ * @returns The builder (for chaining).
759
+ */
760
+ example(cmd: string, description?: string): CommandBuilder<F, A, C>;
761
+ /**
762
+ * Register a named flag on this command.
763
+ *
764
+ * The flag name is added to the type-level `F` map. Duplicate flag names
765
+ * are prevented at the type level via the `Exclude` constraint.
766
+ *
767
+ * The builder controls the flag's type, presence, aliases, env/config
768
+ * bindings, and description. See {@link FlagBuilder} for available modifiers.
769
+ *
770
+ * @param name - Flag name (used as `--name` on CLI and `flags.*` in handler).
771
+ * @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
772
+ * `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
773
+ *
774
+ * @example
775
+ * ```ts
776
+ * command('serve')
777
+ * .flag('port', flag.number()
778
+ * .alias('p')
779
+ * .env('PORT')
780
+ * .default(3000)
781
+ * .describe('Port to listen on'))
782
+ * .flag('host', flag.string()
783
+ * .env('HOST')
784
+ * .default('localhost')
785
+ * .describe('Bind address'))
786
+ * .flag('verbose', flag.boolean()
787
+ * .alias('v')
788
+ * .describe('Enable verbose logging'))
789
+ * .action(({ flags, out }) => {
790
+ * flags.port; // number
791
+ * flags.host; // string
792
+ * flags.verbose; // boolean
793
+ * out.log(`Listening on ${flags.host}:${flags.port}`);
794
+ * });
795
+ *
796
+ * // $ mycli serve --port 8080 -v
797
+ * // $ PORT=9090 mycli serve
798
+ * ```
799
+ *
800
+ * @returns The builder (for chaining).
801
+ */
802
+ flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof F>, builder: B): CommandBuilder<F & Record<N, B>, A, C>;
803
+ /**
804
+ * Register a named positional argument on this command.
805
+ *
806
+ * Args are ordered by registration — position on the CLI matches the
807
+ * order of `.arg()` calls. The arg name is added to the type-level `A`
808
+ * map. Duplicate arg names are prevented at the type level via the
809
+ * `Exclude` constraint.
810
+ *
811
+ * The builder controls the arg's type, presence, env binding, and
812
+ * description. See {@link ArgBuilder} for available modifiers.
813
+ *
814
+ * @param name - Positional arg name (used in help text and `args.*`).
815
+ * @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
816
+ * or `arg.custom()`.
817
+ *
818
+ * @example
819
+ * ```ts
820
+ * command('deploy')
821
+ * // Required string arg — first positional
822
+ * .arg('target', arg.string()
823
+ * .env('DEPLOY_TARGET')
824
+ * .describe('Deploy target'))
825
+ * // Optional number arg — second positional
826
+ * .arg('port', arg.number()
827
+ * .env('PORT')
828
+ * .default(3000)
829
+ * .describe('Port number'))
830
+ * .action(({ args }) => {
831
+ * args.target; // string
832
+ * args.port; // number
833
+ * });
834
+ *
835
+ * // Usage: deploy [flags] <target> [port]
836
+ * // $ mycli deploy production 8080
837
+ * // $ DEPLOY_TARGET=staging mycli deploy
838
+ * ```
839
+ *
840
+ * @returns The builder (for chaining).
841
+ */
842
+ arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
843
+ /**
844
+ * Register a nested subcommand on this command.
845
+ *
846
+ * The subcommand's builder is stored in `_subcommands` for the CLI layer's
847
+ * `eraseCommand()` to traverse when building the execution tree. The
848
+ * subcommand's `CommandSchema` is also appended to `schema.commands` for
849
+ * help rendering and completion generation.
850
+ *
851
+ * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
852
+ * parent level (same semantics as `CLIBuilder.command()`). The handler is
853
+ * preserved.
854
+ *
855
+ * @example
856
+ * ```ts
857
+ * const db = group('db')
858
+ * .description('Database operations')
859
+ * .command(migrateCmd)
860
+ * .command(seedCmd);
861
+ * ```
862
+ *
863
+ * @param sub - Child {@link CommandBuilder} to nest under this command.
864
+ * @returns The builder (for chaining).
865
+ */
866
+ command<F2 extends Record<string, FlagBuilder<FlagConfig>>, A2 extends Record<string, ArgBuilder<ArgConfig>>, C2 extends Record<string, unknown>>(sub: CommandBuilder<F2, A2, C2>): CommandBuilder<F, A, C>;
867
+ /**
868
+ * Register the action handler for this command.
869
+ *
870
+ * The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
871
+ * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
872
+ * definitions.
873
+ *
874
+ * May be synchronous or async. Return values are ignored; command handlers
875
+ * communicate through `out`, thrown errors, and side effects.
876
+ *
877
+ * @param handler - Function receiving `ActionParams<F, A, C>`.
878
+ *
879
+ * @example
880
+ * ```ts
881
+ * // Minimal
882
+ * command('greet')
883
+ * .arg('name', arg.string())
884
+ * .action(({ args, out }) => {
885
+ * out.log(`Hello, ${args.name}!`);
886
+ * });
887
+ * ```
888
+ *
889
+ * @example
890
+ * ```ts
891
+ * // Full params — flags, args, context, output, metadata
892
+ * command('deploy')
893
+ * .arg('target', arg.string().env('DEPLOY_TARGET'))
894
+ * .flag('force', flag.boolean().alias('f'))
895
+ * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
896
+ * .middleware(auth)
897
+ * .action(async ({ args, flags, ctx, out, meta }) => {
898
+ * args.target; // string
899
+ * flags.force; // boolean
900
+ * flags.region; // 'us' | 'eu' | 'ap' | undefined
901
+ * ctx.user; // User (from auth middleware)
902
+ * meta.command; // string
903
+ *
904
+ * const spinner = out.spinner('Deploying...');
905
+ * await deploy(args.target, { force: flags.force });
906
+ * spinner.stop();
907
+ * out.log('Done');
908
+ * });
909
+ * ```
910
+ *
911
+ * @returns The builder (for chaining).
912
+ */
913
+ action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
914
+ }
915
+ /**
916
+ * Create a new command builder.
917
+ *
918
+ * @param name - The command name used for dispatch (e.g. `'deploy'`).
919
+ *
920
+ * @example
921
+ * ```ts
922
+ * import { arg, command, flag } from '@kjanat/dreamcli';
923
+ *
924
+ * const greet = command('greet')
925
+ * .arg('name', arg.string())
926
+ * .flag('loud', flag.boolean())
927
+ * .action(({ args, flags, out }) => {
928
+ * const msg = `Hello, ${args.name}!`;
929
+ * out.log(flags.loud ? msg.toUpperCase() : msg);
930
+ * });
931
+ * ```
932
+ *
933
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
934
+ */
935
+ declare function command(name: string): CommandBuilder;
936
+ /**
937
+ * Create a command builder intended for use as a command group.
938
+ *
939
+ * Semantically identical to {@linkcode command | command()} — a group is simply a command that
940
+ * has subcommands registered via `.command()`. The separate factory
941
+ * communicates intent: groups organise subcommands, leaf commands have actions.
942
+ *
943
+ * A group may also have its own `.action()` (e.g. `git remote` lists remotes
944
+ * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
945
+ *
946
+ * @param name - The group name used for dispatch (e.g. `'db'`).
947
+ *
948
+ * @example
949
+ * ```ts
950
+ * const db = group('db')
951
+ * .description('Database operations')
952
+ * .command(migrateCmd)
953
+ * .command(seedCmd);
954
+ * ```
955
+ *
956
+ * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
957
+ */
958
+ declare function group(name: string): CommandBuilder;
959
+ //#endregion
960
+ export { type ActionHandler, type ActionParams, type AnyCommandBuilder, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type DeriveHandler, type DeriveParams, type ErasedActionHandler, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Out, type RunnableCommand, type WidenContext, type WidenDerivedContext, command, group };