@kjanat/dreamcli 4.0.0-rc.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +5 -7
  2. package/dist/{runtime/adapter.d.mts → adapter-D0hbBNVB.d.mts} +2 -4
  3. package/dist/completion-D4mz6axB.mjs +6 -0
  4. package/dist/completion.d.mts +90 -0
  5. package/dist/completion.mjs +1 -0
  6. package/dist/config-B9ddC-Kb.mjs +1 -0
  7. package/dist/config.d.mts +2 -0
  8. package/dist/config.mjs +1 -0
  9. package/dist/core-Cp2w8vRq.mjs +17 -0
  10. package/dist/index-BziI2aKc.d.mts +5440 -0
  11. package/dist/index-DOfClfYR.d.mts +370 -0
  12. package/dist/index-DWsnGZlx.d.mts +831 -0
  13. package/dist/{core/cli/index.d.mts → index-DXROeDPC.d.mts} +116 -57
  14. package/dist/index-DndPmT8J.d.mts +275 -0
  15. package/dist/{core/json-schema/index.d.mts → index-DyoaS234.d.mts} +43 -34
  16. package/dist/index.d.mts +190 -41
  17. package/dist/index.mjs +1 -26
  18. package/dist/json-schema-C9SzZ7jY.mjs +52 -0
  19. package/dist/json-schema.d.mts +2 -0
  20. package/dist/json-schema.mjs +1 -0
  21. package/dist/package-json-BgE9YjjQ.mjs +3 -0
  22. package/dist/prompt.d.mts +48 -0
  23. package/dist/prompt.mjs +1 -0
  24. package/dist/rolldown-runtime-G4Kt5YOX.mjs +1 -0
  25. package/dist/runtime.d.mts +2 -6
  26. package/dist/runtime.mjs +1 -6
  27. package/dist/terminal-C8KTXjv5.mjs +6 -0
  28. package/dist/test-prompter-v__jT2yG.mjs +1 -0
  29. package/dist/testkit.d.mts +54 -6
  30. package/dist/testkit.mjs +1 -5
  31. package/dist/version.mjs +1 -7
  32. package/dreamcli.schema.json +697 -538
  33. package/package.json +29 -7
  34. package/skills/cli-creation/SKILL.md +16 -11
  35. package/CHANGELOG.md +0 -1116
  36. package/dist/core/cli/builtins.d.mts +0 -117
  37. package/dist/core/cli/builtins.mjs +0 -135
  38. package/dist/core/cli/compiled.d.mts +0 -66
  39. package/dist/core/cli/compiled.mjs +0 -76
  40. package/dist/core/cli/dispatch.d.mts +0 -115
  41. package/dist/core/cli/dispatch.mjs +0 -205
  42. package/dist/core/cli/help-links.d.mts +0 -27
  43. package/dist/core/cli/help-links.mjs +0 -41
  44. package/dist/core/cli/index.mjs +0 -1271
  45. package/dist/core/cli/planner.d.mts +0 -174
  46. package/dist/core/cli/planner.mjs +0 -323
  47. package/dist/core/cli/plugin.d.mts +0 -94
  48. package/dist/core/cli/plugin.mjs +0 -41
  49. package/dist/core/cli/propagate.d.mts +0 -39
  50. package/dist/core/cli/propagate.mjs +0 -57
  51. package/dist/core/cli/reserved-flags.d.mts +0 -19
  52. package/dist/core/cli/reserved-flags.mjs +0 -158
  53. package/dist/core/cli/root-help.d.mts +0 -53
  54. package/dist/core/cli/root-help.mjs +0 -221
  55. package/dist/core/cli/root-output-flags.d.mts +0 -74
  56. package/dist/core/cli/root-output-flags.mjs +0 -169
  57. package/dist/core/cli/root-surface.d.mts +0 -64
  58. package/dist/core/cli/root-surface.mjs +0 -28
  59. package/dist/core/cli/runtime-preflight.d.mts +0 -213
  60. package/dist/core/cli/runtime-preflight.mjs +0 -221
  61. package/dist/core/completion/index.d.mts +0 -76
  62. package/dist/core/completion/index.mjs +0 -90
  63. package/dist/core/completion/shells/bash.d.mts +0 -23
  64. package/dist/core/completion/shells/bash.mjs +0 -312
  65. package/dist/core/completion/shells/fish.d.mts +0 -19
  66. package/dist/core/completion/shells/fish.mjs +0 -164
  67. package/dist/core/completion/shells/powershell.d.mts +0 -13
  68. package/dist/core/completion/shells/powershell.mjs +0 -360
  69. package/dist/core/completion/shells/shared.d.mts +0 -164
  70. package/dist/core/completion/shells/shared.mjs +0 -147
  71. package/dist/core/completion/shells/zsh.d.mts +0 -23
  72. package/dist/core/completion/shells/zsh.mjs +0 -256
  73. package/dist/core/config/index.d.mts +0 -191
  74. package/dist/core/config/index.mjs +0 -285
  75. package/dist/core/config/package-json.d.mts +0 -179
  76. package/dist/core/config/package-json.mjs +0 -353
  77. package/dist/core/errors/index.d.mts +0 -125
  78. package/dist/core/errors/index.mjs +0 -87
  79. package/dist/core/execution/index.d.mts +0 -61
  80. package/dist/core/execution/index.mjs +0 -220
  81. package/dist/core/help/ansi.d.mts +0 -84
  82. package/dist/core/help/ansi.mjs +0 -121
  83. package/dist/core/help/index.d.mts +0 -149
  84. package/dist/core/help/index.mjs +0 -418
  85. package/dist/core/help/theme.d.mts +0 -86
  86. package/dist/core/help/theme.mjs +0 -69
  87. package/dist/core/json-schema/index.mjs +0 -1008
  88. package/dist/core/json-schema/meta-descriptions.generated.d.mts +0 -274
  89. package/dist/core/json-schema/meta-descriptions.generated.mjs +0 -136
  90. package/dist/core/output/activity.d.mts +0 -193
  91. package/dist/core/output/activity.mjs +0 -452
  92. package/dist/core/output/bind.d.mts +0 -37
  93. package/dist/core/output/bind.mjs +0 -56
  94. package/dist/core/output/contracts.d.mts +0 -82
  95. package/dist/core/output/contracts.mjs +0 -57
  96. package/dist/core/output/display-value.d.mts +0 -19
  97. package/dist/core/output/display-value.mjs +0 -32
  98. package/dist/core/output/index.d.mts +0 -344
  99. package/dist/core/output/index.mjs +0 -514
  100. package/dist/core/output/renderers.d.mts +0 -45
  101. package/dist/core/output/renderers.mjs +0 -46
  102. package/dist/core/output/writer.d.mts +0 -39
  103. package/dist/core/output/writer.mjs +0 -12
  104. package/dist/core/parse/index.d.mts +0 -178
  105. package/dist/core/parse/index.mjs +0 -850
  106. package/dist/core/parse/occurrences.d.mts +0 -90
  107. package/dist/core/parse/occurrences.mjs +0 -114
  108. package/dist/core/prompt/index.d.mts +0 -213
  109. package/dist/core/prompt/index.mjs +0 -348
  110. package/dist/core/read-flags/index.d.mts +0 -150
  111. package/dist/core/read-flags/index.mjs +0 -217
  112. package/dist/core/resolve/args.d.mts +0 -39
  113. package/dist/core/resolve/args.mjs +0 -182
  114. package/dist/core/resolve/coerce.d.mts +0 -79
  115. package/dist/core/resolve/coerce.mjs +0 -900
  116. package/dist/core/resolve/config.d.mts +0 -10
  117. package/dist/core/resolve/config.mjs +0 -19
  118. package/dist/core/resolve/contracts.d.mts +0 -146
  119. package/dist/core/resolve/errors.d.mts +0 -10
  120. package/dist/core/resolve/errors.mjs +0 -148
  121. package/dist/core/resolve/flags.d.mts +0 -74
  122. package/dist/core/resolve/flags.mjs +0 -246
  123. package/dist/core/resolve/index.d.mts +0 -44
  124. package/dist/core/resolve/index.mjs +0 -123
  125. package/dist/core/resolve/path-checks.d.mts +0 -48
  126. package/dist/core/resolve/path-checks.mjs +0 -102
  127. package/dist/core/resolve/redaction.d.mts +0 -13
  128. package/dist/core/resolve/redaction.mjs +0 -14
  129. package/dist/core/resolve/stages.d.mts +0 -86
  130. package/dist/core/resolve/stages.mjs +0 -170
  131. package/dist/core/resolve/standard.d.mts +0 -26
  132. package/dist/core/resolve/standard.mjs +0 -212
  133. package/dist/core/schema/activity.d.mts +0 -189
  134. package/dist/core/schema/arg.d.mts +0 -1461
  135. package/dist/core/schema/arg.mjs +0 -1139
  136. package/dist/core/schema/brand.d.mts +0 -17
  137. package/dist/core/schema/cardinality.d.mts +0 -302
  138. package/dist/core/schema/cardinality.mjs +0 -514
  139. package/dist/core/schema/command.d.mts +0 -1132
  140. package/dist/core/schema/command.mjs +0 -999
  141. package/dist/core/schema/flag.d.mts +0 -1495
  142. package/dist/core/schema/flag.mjs +0 -1207
  143. package/dist/core/schema/index.d.mts +0 -15
  144. package/dist/core/schema/index.mjs +0 -10
  145. package/dist/core/schema/middleware.d.mts +0 -129
  146. package/dist/core/schema/middleware.mjs +0 -41
  147. package/dist/core/schema/number-constraints.d.mts +0 -96
  148. package/dist/core/schema/number-constraints.mjs +0 -60
  149. package/dist/core/schema/prompt.d.mts +0 -135
  150. package/dist/core/schema/provenance.d.mts +0 -99
  151. package/dist/core/schema/provenance.mjs +0 -28
  152. package/dist/core/schema/run.d.mts +0 -211
  153. package/dist/core/schema/source.d.mts +0 -180
  154. package/dist/core/schema/source.mjs +0 -206
  155. package/dist/core/schema/standard.d.mts +0 -100
  156. package/dist/core/schema/standard.mjs +0 -15
  157. package/dist/core/schema/stdin.d.mts +0 -97
  158. package/dist/core/schema/stdin.mjs +0 -91
  159. package/dist/core/schema/string-constraints.d.mts +0 -108
  160. package/dist/core/schema/string-constraints.mjs +0 -86
  161. package/dist/core/schema/value-parsers.d.mts +0 -150
  162. package/dist/core/schema/value-parsers.mjs +0 -160
  163. package/dist/core/schema/value.d.mts +0 -243
  164. package/dist/core/schema/value.mjs +0 -573
  165. package/dist/core/testkit/index.d.mts +0 -63
  166. package/dist/core/testkit/index.mjs +0 -102
  167. package/dist/runtime/adapter.mjs +0 -92
  168. package/dist/runtime/auto.d.mts +0 -25
  169. package/dist/runtime/auto.mjs +0 -45
  170. package/dist/runtime/deno.d.mts +0 -99
  171. package/dist/runtime/deno.mjs +0 -265
  172. package/dist/runtime/detect.d.mts +0 -86
  173. package/dist/runtime/detect.mjs +0 -45
  174. package/dist/runtime/index.d.mts +0 -6
  175. package/dist/runtime/node.d.mts +0 -71
  176. package/dist/runtime/node.mjs +0 -228
  177. package/dist/runtime/paths.d.mts +0 -31
  178. package/dist/runtime/paths.mjs +0 -48
  179. package/dist/strings.d.mts +0 -27
  180. package/dist/strings.mjs +0 -22
  181. package/examples/basic.ts +0 -37
  182. package/examples/flag-types.ts +0 -79
  183. package/examples/gh/package.json +0 -45
  184. package/examples/gh/src/commands/auth.ts +0 -66
  185. package/examples/gh/src/commands/issue.ts +0 -120
  186. package/examples/gh/src/commands/pr.ts +0 -125
  187. package/examples/gh/src/data/issues.yaml +0 -5
  188. package/examples/gh/src/data/issues.yaml.d.ts +0 -17
  189. package/examples/gh/src/data/pull-requests.yaml +0 -7
  190. package/examples/gh/src/data/pull-requests.yaml.d.ts +0 -18
  191. package/examples/gh/src/docs.ts +0 -11
  192. package/examples/gh/src/lib/auth.ts +0 -37
  193. package/examples/gh/src/lib/utils.ts +0 -17
  194. package/examples/gh/src/main.test.ts +0 -307
  195. package/examples/gh/src/main.ts +0 -46
  196. package/examples/help-config.ts +0 -43
  197. package/examples/interactive.ts +0 -67
  198. package/examples/json-mode.ts +0 -95
  199. package/examples/middleware.ts +0 -71
  200. package/examples/multi-command.ts +0 -66
  201. package/examples/output-extras.ts +0 -46
  202. package/examples/parser-control.ts +0 -40
  203. package/examples/pwsh-demo/README.md +0 -40
  204. package/examples/pwsh-demo/package.json +0 -41
  205. package/examples/pwsh-demo/pwsh-demo.cmd +0 -3
  206. package/examples/pwsh-demo/smoke-powershell.ps1 +0 -218
  207. package/examples/pwsh-demo/src/main.test.ts +0 -45
  208. package/examples/pwsh-demo/src/main.ts +0 -140
  209. package/examples/spinner-progress.ts +0 -49
  210. package/examples/standard-schema.ts +0 -45
  211. package/examples/testing.ts +0 -147
  212. package/examples/transport-launcher.ts +0 -85
@@ -1,1132 +0,0 @@
1
- import { schemaBrand } from "./brand.mjs";
2
- import { PromptConfig } from "./prompt.mjs";
3
- import { FlagBuilder, FlagConfig, FlagDefinition, FlagSchema, InferFlags } from "./flag.mjs";
4
- import { ArgBuilder, ArgConfig, ArgDefinition, ArgSchema, InferArgs } from "./arg.mjs";
5
- import { ProgressHandle, ProgressOptions, SpinnerHandle, SpinnerOptions, TableColumn, TableOptions } from "./activity.mjs";
6
- import { Verbosity } from "../output/contracts.mjs";
7
- import { ErasedMiddlewareHandler, Middleware } from "./middleware.mjs";
8
- import { InputSources } from "./provenance.mjs";
9
- import { Colors } from "ansispeck";
10
- //#region src/core/schema/command.d.ts
11
- /**
12
- * Widen the context type when adding middleware.
13
- *
14
- * The default `C = Record<string, never>` uses an index signature where
15
- * every key maps to `never` — making property access a type error until
16
- * middleware extends it. Naive intersection (`Record<string, never> & { user: string }`)
17
- * collapses all properties to `never` because `never & T = never`.
18
- *
19
- * This utility replaces `Record<string, never>` entirely on the first
20
- * `.middleware()` call. Subsequent calls use plain intersection.
21
- */
22
- type WidenContext<C extends Record<string, unknown>, Output extends Record<string, unknown>> = C extends Record<string, never> ? Output : C & Output;
23
- /**
24
- * Widen the context type when adding command-scoped derived context.
25
- *
26
- * Validation-only derive handlers return `undefined` (or nothing), preserving `C`.
27
- * Context-producing derive handlers return an object that merges into `C`
28
- * using the same first-call replacement rules as middleware.
29
- */
30
- type WidenDerivedContext<C extends Record<string, unknown>, Output> = Awaited<Output> extends Record<string, unknown> ? WidenContext<C, Awaited<Output>> : C;
31
- /**
32
- * Parameters received by the interactive resolver function.
33
- *
34
- * `flags` contains partially resolved values — present for flags resolved
35
- * via CLI, env, or config, `undefined` for unresolved flags. The resolver
36
- * uses this to decide which prompts to show based on current state.
37
- */
38
- interface InteractiveParams<F extends Record<string, FlagBuilder<FlagConfig>>> {
39
- /** Partially resolved flag values (after CLI/env/config, before prompts). */
40
- readonly flags: Readonly<Partial<InferFlags<F>>>;
41
- }
42
- /**
43
- * A record mapping flag names to prompt configs or falsy values.
44
- *
45
- * - `PromptConfig` — show this prompt for the flag
46
- * - `false | undefined | null | 0 | ''` — skip prompting for this flag
47
- *
48
- * Only flag names that need prompting should have truthy values.
49
- * Flags not mentioned are handled by their per-flag `.prompt()` config.
50
- */
51
- type InteractiveResult = Readonly<Record<string, PromptConfig | false | undefined | null | 0 | ''>>;
52
- /**
53
- * Interactive resolver function for command-level prompt control.
54
- *
55
- * Called after CLI/env/config resolution but before per-flag prompts fire.
56
- * Receives partially resolved values and returns a prompt schema for
57
- * flags that should be prompted. Commands without `.interactive()` use
58
- * per-flag prompt configs directly.
59
- *
60
- * @example
61
- * ```ts
62
- * import { command, flag } from '@kjanat/dreamcli';
63
- *
64
- * const deploy = command('deploy')
65
- * .flag('region', flag.enum(['us', 'eu', 'ap']))
66
- * .interactive(({ flags }) => ({
67
- * region: !flags.region && {
68
- * kind: 'select',
69
- * message: 'Select region',
70
- * },
71
- * }))
72
- * .action(({ flags, out }) => {
73
- * out.log(`Deploying to ${flags.region}`);
74
- * });
75
- * ```
76
- */
77
- type InteractiveResolver<F extends Record<string, FlagBuilder<FlagConfig>>> = (params: InteractiveParams<F>) => InteractiveResult;
78
- /**
79
- * Type-erased interactive resolver stored on {@linkcode CommandSchema}.
80
- *
81
- * Advanced bridge type: most consumers should use {@link InteractiveResolver}
82
- * via {@linkcode command | command().interactive()} and never reference this alias directly.
83
- *
84
- * At runtime, the resolver receives `{ flags: Record<string, unknown> }`
85
- * and returns `Record<string, PromptConfig | falsy>`. The phantom types
86
- * from `CommandBuilder<F, A>` are erased.
87
- */
88
- type ErasedInteractiveResolver = (params: {
89
- readonly flags: Readonly<Record<string, unknown>>;
90
- }) => InteractiveResult;
91
- /**
92
- * Seals {@linkcode Out} against structural construction outside the framework.
93
- *
94
- * @internal
95
- */
96
- declare const outBrand: unique symbol;
97
- /**
98
- * Output channel available inside action handlers.
99
- *
100
- * Provides structured methods for stdout/stderr, JSON output,
101
- * spinners, progress bars, and tables. The real implementation lives in
102
- * `src/core/output/`; this interface defines the shape that handlers consume.
103
- *
104
- * `Out` is a framework-created, non-exhaustive value: obtain instances from
105
- * action parameters, `createOutput()`, or `createCaptureOutput()` — do not
106
- * implement it. New readonly members may be added in minor releases.
107
- */
108
- interface Out {
109
- /** Framework-construction seal. Obtain `Out` values from DreamCLI; do not implement this interface. */
110
- readonly [outBrand]: never;
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
- /**
116
- * Status line to stderr, suppressed in quiet mode.
117
- *
118
- * Keeps stdout clean for piping; for success and progress notes like
119
- * `Wrote <path>` that scripts silence with `--quiet`.
120
- */
121
- status(message: string): void;
122
- /** Warning to stderr. */
123
- warn(message: string): void;
124
- /** Error to stderr. */
125
- error(message: string): void;
126
- /**
127
- * Request a process exit code without emitting error-shaped output.
128
- *
129
- * Use this for check/status commands that should print normal output but
130
- * still signal a non-zero status to scripts. This does not stop execution;
131
- * later calls overwrite earlier calls, and thrown errors still win.
132
- */
133
- setExitCode(code: number): void;
134
- /**
135
- * Emit a structured JSON value to stdout.
136
- *
137
- * Always serialises `value` as JSON to stdout regardless of output
138
- * mode. Prefer this over `log(JSON.stringify(...))` so the output
139
- * channel can enforce consistent formatting and future features
140
- * (pretty-print in TTY, streaming JSON, etc.).
141
- */
142
- json(value: unknown): void;
143
- /**
144
- * Whether the output channel is in JSON mode (`--json` flag active).
145
- *
146
- * Handlers can check this to skip decorative output (spinners,
147
- * progress bars, ANSI formatting) when machine-readable output is
148
- * expected.
149
- */
150
- readonly jsonMode: boolean;
151
- /**
152
- * Active output verbosity for this command execution.
153
- *
154
- * Root `--quiet`/`-q` resolves to `'quiet'`. Most handlers should emit
155
- * informational output through {@linkcode Out.info | info()},
156
- * {@linkcode Out.status | status()}, {@linkcode Out.spinner | spinner()},
157
- * or {@linkcode Out.progress | progress()} and let the channel suppress it
158
- * automatically. Read this property only when custom rendering or expensive
159
- * optional work genuinely depends on the active verbosity.
160
- */
161
- readonly verbosity: Verbosity;
162
- /**
163
- * Whether stdout is connected to a TTY (terminal).
164
- *
165
- * Handlers can check this to decide whether to emit decorative output
166
- * (spinners, progress bars, ANSI color codes). When `false`, the output
167
- * is being piped or redirected — skip interactive decorations.
168
- *
169
- * Note: `jsonMode` takes precedence — when `jsonMode` is `true`,
170
- * decorative output should be suppressed regardless of `isTTY`.
171
- */
172
- readonly isTTY: boolean;
173
- /**
174
- * Context-aware ANSI color palette (powered by `ansispeck`).
175
- *
176
- * Colors are enabled only when stdout is a TTY, JSON mode is off, and the
177
- * environment supports color (`NO_COLOR`, `FORCE_COLOR`, `--no-color`,
178
- * `--color`, `CI` are respected). When disabled, every formatter is an
179
- * identity function — `out.color.red('x')` returns `'x'` — so handlers can
180
- * style unconditionally without gating on `isTTY`/`jsonMode` themselves.
181
- *
182
- * @example
183
- * ```ts
184
- * .action(({ out }) => {
185
- * out.log(`${out.color.green('✔')} deployed ${out.color.bold('api')}`);
186
- * });
187
- * ```
188
- */
189
- readonly color: Colors;
190
- /**
191
- * Whether OSC 8 terminal hyperlinks should be emitted.
192
- *
193
- * Honors explicit `--no-hyperlinks`/`--hyperlinks` argv flags first, then
194
- * `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, falling back to `isTTY`.
195
- * Handlers rendering their own `out.color.link(...)` output can gate on
196
- * this to keep OSC 8 escapes out of piped or opted-out contexts.
197
- */
198
- readonly isHyperlinkSupported: boolean;
199
- /**
200
- * Render tabular data.
201
- *
202
- * - **TTY mode** (non-JSON): Pretty-print aligned columns with headers.
203
- * - **JSON mode** (`--json`): Emit the rows as a JSON array to stdout.
204
- * - **Piped** (non-TTY, non-JSON): Same aligned text output as TTY
205
- * (useful for `grep`, `awk`, etc.).
206
- * - Pass `{ format: 'text', stream: 'stderr' }` to keep a human-readable
207
- * side channel while `json()` writes machine output to stdout.
208
- *
209
- * When `columns` is omitted, columns are auto-inferred from the keys
210
- * of the first row. Column headers default to the key name.
211
- *
212
- * When `columns` is provided, both text and JSON output are projected to
213
- * only the listed keys.
214
- *
215
- * @param rows - Array of row objects.
216
- */
217
- table<T extends Record<string, unknown>>(rows: readonly T[], options: TableOptions): void;
218
- /**
219
- * Render tabular data with explicit column selection.
220
- *
221
- * @param rows - Array of row objects.
222
- * @param columns - Column descriptors controlling which keys are shown and header labels.
223
- * @param options - Per-call rendering options (format, stream).
224
- */
225
- table<T extends Record<string, unknown>>(rows: readonly T[], columns?: readonly TableColumn<T>[], options?: TableOptions): void;
226
- /**
227
- * Create a spinner for indeterminate progress feedback.
228
- *
229
- * Returns a no-op handle in quiet or JSON mode. Otherwise, non-TTY output
230
- * uses a no-op handle or the configured static fallback.
231
- *
232
- * @param text - Initial spinner text.
233
- * @param options - Fallback strategy for non-TTY environments.
234
- * @returns A {@link SpinnerHandle} for lifecycle control.
235
- */
236
- spinner(text: string, options?: SpinnerOptions): SpinnerHandle;
237
- /**
238
- * Create a progress bar for measured work.
239
- *
240
- * Returns a no-op handle in quiet or JSON mode. Otherwise, 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
- * Stop the currently active spinner or progress handle, if any.
249
- *
250
- * TTY spinner and progress handles start `setInterval` timers that
251
- * prevent the process from exiting until a terminal method (`stop`,
252
- * `succeed`, `fail`, `done`) is called. If a handler throws before
253
- * reaching that call, the timer leaks and the process hangs.
254
- *
255
- * Call `stopActive()` in a `finally` block after handler execution
256
- * to guarantee cleanup. It is idempotent — safe to call when no
257
- * handle is active, or when the handle was already stopped.
258
- *
259
- * The framework calls this automatically in `runCommand()` and
260
- * `cli().run()`. Direct users of `createOutput()` should call it
261
- * themselves after the handler returns or throws.
262
- *
263
- * @example
264
- * ```ts
265
- * const out = createOutput({ isTTY: true });
266
- * try {
267
- * await handler({ out });
268
- * } finally {
269
- * out.stopActive();
270
- * }
271
- * ```
272
- */
273
- stopActive(): void;
274
- }
275
- /**
276
- * Runtime metadata about the CLI program and current command execution.
277
- *
278
- * Available to action handlers and middleware.
279
- *
280
- * Populated by the CLI dispatch layer from {@link CLISchema} and
281
- * {@link CommandSchema}. For standalone `runCommand()` calls without
282
- * a CLI wrapper, a minimal meta is constructed from the command's own schema.
283
- */
284
- interface CommandMeta {
285
- /** CLI program name (from `cli('name')` or package.json inference). */
286
- readonly name: string;
287
- /** Binary display name used in help/usage (may differ from `name`). */
288
- readonly bin: string;
289
- /** Program version, if set via `.version()` or discovered from package.json. */
290
- readonly version: string | undefined;
291
- /** The leaf command name currently being executed. */
292
- readonly command: string;
293
- }
294
- /**
295
- * The bag of values received by an action handler.
296
- *
297
- * - `args`: fully resolved positional arguments
298
- * - `flags`: fully resolved flags
299
- * - `sources`: which stage produced each of those values
300
- * - `ctx`: derive/middleware-provided context
301
- * - `out`: output channel
302
- * - `meta`: CLI program metadata (name, bin, version, command)
303
- *
304
- * The `C` parameter defaults to `Record<string, never>`, making `ctx`
305
- * property access a type error until derive or middleware extends it.
306
- */
307
- interface ActionParams<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>> {
308
- /** Fully resolved positional argument values, typed from `.arg()` definitions. */
309
- readonly args: Readonly<InferArgs<A>>;
310
- /** Fully resolved flag values, typed from `.flag()` definitions. */
311
- readonly flags: Readonly<InferFlags<F>>;
312
- /**
313
- * Where each resolved value came from, keyed like `flags` and `args`.
314
- *
315
- * An input that resolved no value has no record. {@link wasExplicit} answers
316
- * the explicit-versus-defaulted question; read `stage` for the rest.
317
- */
318
- readonly sources: InputSources<F, A>;
319
- /** Middleware/derive-provided context, typed from `.middleware()` and `.derive()` chains. */
320
- readonly ctx: Readonly<C>;
321
- /** Structured output channel for stdout, stderr, JSON, tables, and spinners. */
322
- readonly out: Out;
323
- /** Runtime metadata about the CLI program and current command. */
324
- readonly meta: CommandMeta;
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<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>;
334
- /**
335
- * Type-erased action handler stored on {@linkcode CommandBuilder}.
336
- *
337
- * The typed {@linkcode ActionHandler} from `.action()` is cast to this
338
- * erased form at the type-erasure boundary, keeping {@linkcode CommandBuilder}
339
- * covariant in its generic parameters. This enables structural
340
- * compatibility across TypeScript declaration-file boundaries where
341
- * generic inference may fall back to constraint types.
342
- *
343
- * Follows the same erasure pattern as {@link ErasedDeriveHandler} and
344
- * {@link ErasedMiddlewareHandler}.
345
- */
346
- type ErasedActionHandler = (params: {
347
- readonly args: Readonly<Record<string, unknown>>;
348
- readonly flags: Readonly<Record<string, unknown>>;
349
- readonly sources: ErasedInputSources;
350
- readonly ctx: Readonly<Record<string, unknown>>;
351
- readonly out: Out;
352
- readonly meta: CommandMeta;
353
- }) => void | Promise<void>;
354
- /**
355
- * The provenance bag as the execution seam carries it, before a handler's own
356
- * flag and arg names type it.
357
- */
358
- type ErasedInputSources = InputSources<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>;
359
- /**
360
- * The bag of values received by a derive handler.
361
- *
362
- * Identical to {@link ActionParams}: derives run after full resolution and
363
- * before the action handler, with typed args, flags, provenance, and current
364
- * context plus `out` and `meta`.
365
- */
366
- 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>;
367
- /**
368
- * Command-scoped typed pre-action handler.
369
- *
370
- * Derive handlers may:
371
- * - validate resolved input and throw {@linkcode CLIError}
372
- * - return nothing (or `undefined`) to continue without changing context
373
- * - return an object whose properties merge into `ctx` downstream
374
- *
375
- * Handlers may be async; the resolved value follows the same rules.
376
- * They cannot wrap downstream execution; use {@linkcode middleware} for that.
377
- */
378
- 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> | void | Promise<void>;
379
- /**
380
- * Type-erased derive handler stored on the command builder.
381
- */
382
- type ErasedDeriveHandler = (params: {
383
- readonly args: Readonly<Record<string, unknown>>;
384
- readonly flags: Readonly<Record<string, unknown>>;
385
- readonly sources: ErasedInputSources;
386
- readonly ctx: Readonly<Record<string, unknown>>;
387
- readonly out: Out;
388
- readonly meta: CommandMeta;
389
- }) => undefined | Readonly<Record<string, unknown>> | Promise<undefined | Readonly<Record<string, unknown>>>;
390
- /**
391
- * Internal execution step union preserving registration order across
392
- * {@linkcode CommandBuilder.derive | derive()} and {@linkcode CommandBuilder.middleware | middleware()}.
393
- */
394
- type ExecutionStep = {
395
- readonly kind: 'derive';
396
- readonly handler: ErasedDeriveHandler;
397
- } | {
398
- readonly kind: 'middleware';
399
- readonly handler: ErasedMiddlewareHandler;
400
- };
401
- /**
402
- * Program metadata passed to a function-form example, resolved at render time.
403
- *
404
- * `name` is the actually-invoked program name (`options.help.binName`, falling
405
- * back to the command name) so examples stay truthful under symlinks,
406
- * `inheritName`, and `npx x` vs a global install. `version` is the program
407
- * version, or `undefined` when none is configured.
408
- */
409
- interface ExampleMeta {
410
- readonly name: string;
411
- readonly version: string | undefined;
412
- }
413
- /**
414
- * An example command line: a literal string, or a function resolved at render
415
- * time with the program {@link ExampleMeta} (so the program name need not be
416
- * hardcoded).
417
- */
418
- type ExampleCommand = string | ((meta: ExampleMeta) => string);
419
- /** A single usage example shown in help text. */
420
- interface CommandExample {
421
- /** The command invocation (e.g. `'deploy production --force'`). */
422
- readonly command: ExampleCommand;
423
- /** Optional description of what this example does. */
424
- readonly description?: string;
425
- }
426
- /** Resolve an {@link ExampleCommand} to its string form for the given meta. */
427
- declare function resolveExampleCommand(command: ExampleCommand, meta: ExampleMeta): string;
428
- /**
429
- * Runtime descriptor produced by {@link CommandBuilder}.
430
- *
431
- * Consumers (parser, help generator, CLI dispatcher) read this to
432
- * understand the command's shape — flags, args, aliases, subcommands,
433
- * and interactive resolver.
434
- */
435
- interface CommandSchema {
436
- /** Type-only seal produced by {@link createCommandSchema}. */
437
- readonly [schemaBrand]: 'command';
438
- /** The command name (used for dispatch, e.g. `'deploy'`). */
439
- readonly name: string;
440
- /** Human-readable description for help text. */
441
- readonly description: string | undefined;
442
- /** Alternative names for this command. */
443
- readonly aliases: readonly string[];
444
- /** Whether this command is hidden from help listings. */
445
- readonly hidden: boolean;
446
- /** Usage examples for help text. */
447
- readonly examples: readonly CommandExample[];
448
- /** Named flag schemas, keyed by flag name. */
449
- readonly flags: Readonly<Record<string, FlagSchema>>;
450
- /** Ordered positional arg entries (name + schema). */
451
- readonly args: readonly CommandArgEntry[];
452
- /** Whether an action handler has been registered. */
453
- readonly hasAction: boolean;
454
- /**
455
- * Command-level interactive resolver for schema-driven prompt control.
456
- *
457
- * When set, called after CLI/env/config resolution with partially resolved
458
- * flag values. Returns prompt configs for flags that need interactive input.
459
- * Takes precedence over per-flag `.prompt()` configs for flags it returns
460
- * configs for; flags not mentioned fall back to their per-flag configs.
461
- *
462
- * @see InteractiveResolver
463
- */
464
- readonly interactive: ErasedInteractiveResolver | undefined;
465
- /**
466
- * Nested subcommand schemas (for help rendering and completion).
467
- *
468
- * Pure data — no execution closures. Populated by `.command()` on
469
- * `CommandBuilder`. Empty for leaf commands.
470
- */
471
- readonly commands: readonly CommandSchema[];
472
- }
473
- /**
474
- * A named positional argument entry in the command schema.
475
- *
476
- * Pairs a user-facing arg name with its {@link ArgSchema} descriptor.
477
- * The array ordering in {@link CommandSchema.args} determines CLI position.
478
- */
479
- interface CommandArgEntry {
480
- /** User-facing argument name (shown in help as `<name>`). */
481
- readonly name: string;
482
- /** Runtime descriptor controlling parsing, presence, and coercion. */
483
- readonly schema: ArgSchema;
484
- }
485
- /**
486
- * A named positional argument entry accepted by {@link createCommandSchema}.
487
- *
488
- * The schema may be an {@link ArgDefinition} or an already-built {@link ArgSchema}.
489
- */
490
- interface CommandArgEntryDefinition {
491
- /** User-facing argument name (shown in help as `<name>`). */
492
- readonly name: string;
493
- /** Arg definition or an already-built schema. */
494
- readonly schema: ArgDefinition | ArgSchema;
495
- }
496
- /**
497
- * Input shape accepted by {@link createCommandSchema}.
498
- *
499
- * Every field except `name` is optional. Flags, args, and subcommands accept
500
- * either definitions or already-built schemas.
501
- */
502
- interface CommandDefinition {
503
- /** The command name used for dispatch. */
504
- readonly name: string;
505
- /**
506
- * Human-readable description for help text.
507
- * @defaultValue `undefined`
508
- */
509
- readonly description?: string | undefined;
510
- /**
511
- * Alternative names for this command.
512
- * @defaultValue `[]`
513
- */
514
- readonly aliases?: readonly string[] | undefined;
515
- /**
516
- * Whether this command is hidden from help listings.
517
- * @defaultValue `false`
518
- */
519
- readonly hidden?: boolean | undefined;
520
- /**
521
- * Usage examples for help text.
522
- * @defaultValue `[]`
523
- */
524
- readonly examples?: readonly CommandExample[] | undefined;
525
- /**
526
- * Flag definitions or built schemas, keyed by flag name.
527
- * @defaultValue `{}`
528
- */
529
- readonly flags?: Readonly<Record<string, FlagDefinition | FlagSchema>> | undefined;
530
- /**
531
- * Ordered positional arg entries.
532
- * @defaultValue `[]`
533
- */
534
- readonly args?: readonly CommandArgEntryDefinition[] | undefined;
535
- /**
536
- * Whether an action handler has been registered.
537
- * @defaultValue `false`
538
- */
539
- readonly hasAction?: boolean | undefined;
540
- /**
541
- * Command-level interactive resolver.
542
- * @defaultValue `undefined`
543
- */
544
- readonly interactive?: ErasedInteractiveResolver | undefined;
545
- /**
546
- * Nested subcommand definitions or built schemas.
547
- * @defaultValue `[]`
548
- */
549
- readonly commands?: readonly (CommandDefinition | CommandSchema)[] | undefined;
550
- }
551
- /**
552
- * Create a {@link CommandSchema} from a plain definition object.
553
- *
554
- * Most consumers should prefer {@link command | command()}, which returns a
555
- * {@link CommandBuilder} with type inference. `createCommandSchema()` is the
556
- * low-level escape hatch for tooling that composes schemas as data.
557
- *
558
- * Flags, args, and subcommands are normalized recursively, so an already-built
559
- * schema fed back in produces a deep-equal schema.
560
- *
561
- * Flag spellings are checked across the whole tree, so a definition whose names,
562
- * aliases, or negated spellings collide with each other or with a propagated
563
- * ancestor flag is rejected here. Both flags still parse under their canonical
564
- * names, so what a collision costs is the shared spelling. Help advertises it on
565
- * both flags and the parser answers it with one of them.
566
- * Args go through the same invariants {@link CommandBuilder.arg} enforces.
567
- * These are the checks the {@link CommandBuilder} applies as flags, args, and
568
- * subcommands are registered.
569
- *
570
- * @param definition - Command name plus optional flags, args, and subcommands.
571
- * @returns A fully populated {@link CommandSchema}.
572
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when a name at any depth is
573
- * empty or contains whitespace, a flag or arg at any depth is named
574
- * `__proto__`, which JavaScript cannot carry as a plain record key, or a flag
575
- * record at any depth has a
576
- * replaced prototype, which hides the entries a name check would read.
577
- * @throws {CLIError} With code `'FLAG_NAME_COLLISION'` when two flags on one
578
- * command share a spelling.
579
- * @throws {CLIError} With code `'PROPAGATED_FLAG_COLLISION'` when a flag shadows
580
- * a spelling propagated from an ancestor command.
581
- * @throws {CLIError} With code `'INVALID_BUILDER_STATE'` when a positional comes
582
- * after a variadic one, or `'DUPLICATE_STDIN_INPUT'` when two inputs on one
583
- * command consume stdin and either is exclusive.
584
- *
585
- * @example
586
- * ```ts
587
- * const schema = createCommandSchema({
588
- * name: 'deploy',
589
- * description: 'Ship the build',
590
- * flags: { force: { kind: 'boolean' } },
591
- * args: [{ name: 'target', schema: { kind: 'string' } }],
592
- * });
593
- * ```
594
- */
595
- declare function createCommandSchema(definition: CommandDefinition): CommandSchema;
596
- /**
597
- * Structural subset of {@linkcode CommandBuilder} accepted by `runCommand()`.
598
- *
599
- * Avoids generic type parameters so any `CommandBuilder<F, A, C>` satisfies
600
- * this interface structurally — no variance constraints, no inference needed.
601
- * The testkit reads `handler` and `_executionSteps` off it and hands them to
602
- * the shared executor, so TypeScript never has to resolve
603
- * {@linkcode CommandBuilder}'s full generic signature.
604
- *
605
- * @internal
606
- */
607
- interface RunnableCommand {
608
- readonly schema: CommandSchema;
609
- readonly handler: ErasedActionHandler | undefined;
610
- readonly _executionSteps: readonly ExecutionStep[];
611
- }
612
- /**
613
- * Type-erased {@link CommandBuilder} for heterogeneous subcommand storage.
614
- *
615
- * Advanced helper alias: useful only when working on DreamCLI internals or
616
- * custom tooling that mirrors the framework's type-erasure boundary.
617
- *
618
- * Uses widest possible generic bounds so any `CommandBuilder<F, A, C>` is
619
- * assignable. The CLI layer's `compileCommand()` traverses these to build
620
- * the execution graph.
621
- *
622
- */
623
- type AnyCommandBuilder = CommandBuilder<Record<string, FlagBuilder<FlagConfig>>, Record<string, ArgBuilder<ArgConfig>>, Record<string, unknown>>;
624
- /**
625
- * Immutable command schema builder.
626
- *
627
- * The type parameters `F` (flags), `A` (args), and `C` (context) are
628
- * phantom types that accumulate builder types as `.flag()`, `.arg()`,
629
- * `.derive()`, and `.middleware()` are chained. The `.action()` handler receives
630
- * fully typed `ActionParams<F, A, C>`.
631
- *
632
- * `C` defaults to `Record<string, never>`, making `ctx` property
633
- * access a type error until derive or middleware extends it.
634
- *
635
- * @example
636
- * ```ts
637
- * const deploy = command('deploy')
638
- * .description('Deploy to an environment')
639
- * .arg('target', arg.string().describe('Deploy target'))
640
- * .flag('force', flag.boolean().alias('f'))
641
- * .flag('region', flag.enum(['us', 'eu', 'ap']))
642
- * .action(async ({ args, flags, out }) => {
643
- * // args.target: string
644
- * // flags.force: boolean
645
- * // flags.region: 'us' | 'eu' | 'ap' | undefined
646
- * out.log(`Deploying ${args.target}...`);
647
- * });
648
- * ```
649
- */
650
- declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> = {}, A extends Record<string, ArgBuilder<ArgConfig>> = {}, C extends Record<string, unknown> = Record<string, never>> {
651
- /** @internal Runtime schema descriptor. */
652
- readonly schema: CommandSchema;
653
- /** @internal The action handler, if registered (type-erased for covariance). */
654
- readonly handler: ErasedActionHandler | undefined;
655
- /**
656
- * @internal Nested sub-command builders (type-erased for heterogeneous storage).
657
- *
658
- * Stored separately from `schema.commands` because builders carry action
659
- * handlers and phantom types needed by `compileCommand()` in the CLI layer.
660
- * `schema.commands` holds pure `CommandSchema[]` for help/completion.
661
- */
662
- readonly _subcommands: readonly AnyCommandBuilder[];
663
- /**
664
- * @internal Derive and middleware steps in registration order.
665
- *
666
- * The executor builds the handler chain from this list.
667
- */
668
- readonly _executionSteps: readonly ExecutionStep[];
669
- /** @internal Phantom brand for accumulated flag builder types. No runtime value. */
670
- readonly _flags: F;
671
- /** @internal Phantom brand for accumulated arg builder types. No runtime value. */
672
- readonly _args: A;
673
- /** @internal Phantom brand for accumulated context type. No runtime value. */
674
- readonly _ctx: C;
675
- /**
676
- * Create a command builder from a pre-built schema descriptor.
677
- *
678
- * @param schema - Runtime command descriptor.
679
- * @param handler - Action handler, if registered.
680
- * @param subcommands - Nested sub-command builders (type-erased).
681
- * @param executionSteps - Derive/middleware steps in registration order.
682
- */
683
- constructor(schema: CommandSchema, handler?: ErasedActionHandler, subcommands?: readonly AnyCommandBuilder[], executionSteps?: readonly ExecutionStep[]);
684
- /**
685
- * Register a command-level interactive resolver for schema-driven prompts.
686
- *
687
- * The resolver is called after CLI/env/config resolution with partially
688
- * resolved flag values. It returns a prompt schema for flags that need
689
- * interactive input based on the current state.
690
- *
691
- * For flags the resolver returns a {@linkcode PromptConfig}, that config is used
692
- * instead of any per-flag `.prompt()` config. For flags returned as falsy
693
- * (or not mentioned), per-flag `.prompt()` configs are used as fallback.
694
- *
695
- * Commands without `.interactive()` use per-flag prompt configs directly.
696
- *
697
- * @example
698
- * ```ts
699
- * const deploy = command('deploy')
700
- * .flag('region', flag.enum(['us', 'eu', 'ap']))
701
- * .flag('force', flag.boolean())
702
- * .interactive(({ flags }) => ({
703
- * region: !flags.region && {
704
- * kind: 'select',
705
- * message: 'Select region',
706
- * },
707
- * }))
708
- * .action(({ flags }) => { ... });
709
- * ```
710
- *
711
- * @param resolver - Function receiving partially resolved flags and returning prompt configs.
712
- * @returns The builder (for chaining).
713
- */
714
- interactive(resolver: InteractiveResolver<F>): CommandBuilder<F, A, C>;
715
- /**
716
- * Register a command-scoped typed pre-action handler.
717
- *
718
- * Derive runs after full resolution and before the action handler.
719
- * It receives typed `{ args, flags, ctx, out, meta }` and may either:
720
- *
721
- * - return nothing (or `undefined`) for validation-only behavior
722
- * - return an object to merge additional properties into `ctx`
723
- *
724
- * Handlers may be async — the runtime awaits them before continuing.
725
- *
726
- * Unlike middleware, derive cannot wrap downstream execution and does not
727
- * use `next()`. Use {@linkcode middleware} for timing, logging, retries, cleanup,
728
- * or error-boundary patterns.
729
- *
730
- * Adding derive drops the current handler (like `.flag()`, `.arg()`, and
731
- * `.middleware()`) because the action handler's `ctx` type may change.
732
- *
733
- * @example
734
- * ```ts
735
- * command('deploy')
736
- * .flag('token', flag.string().env('AUTH_TOKEN'))
737
- * .derive(({ flags }) => {
738
- * if (!flags.token) {
739
- * throw new CLIError('Not authenticated', {
740
- * code: 'AUTH_REQUIRED',
741
- * suggest: 'Run `mycli login` or set AUTH_TOKEN',
742
- * });
743
- * }
744
- * return { token: flags.token };
745
- * })
746
- * .action(({ ctx }) => {
747
- * ctx.token; // string
748
- * });
749
- * ```
750
- *
751
- * @param handler - Derive function receiving typed args/flags/ctx.
752
- * @returns The builder (for chaining).
753
- */
754
- derive<Output extends Record<string, unknown> | undefined = undefined>(handler: DeriveHandler<F, A, C, Output>): CommandBuilder<F, A, WidenDerivedContext<C, Output>>;
755
- /**
756
- * Register middleware to run before the action handler.
757
- *
758
- * Middleware executes in registration order. Each middleware receives
759
- * `{ args, flags, ctx, out, meta, next }` and must call `next(additions)`
760
- * to continue the chain. Context additions are merged and become
761
- * typed downstream.
762
- *
763
- * Adding middleware widens `C` via intersection and drops the current
764
- * handler (like `.flag()` / `.arg()` — the handler's type signature
765
- * changes when context changes).
766
- *
767
- * @example
768
- * ```ts
769
- * import { CLIError, command, middleware } from '@kjanat/dreamcli';
770
- *
771
- * interface User {
772
- * id: string;
773
- * email: string;
774
- * }
775
- *
776
- * async function getCurrentUser(): Promise<User | null> {
777
- * return { id: 'u_123', email: 'dev@example.com' };
778
- * }
779
- *
780
- * function startTrace(name: string): string {
781
- * return `trace:${name}`;
782
- * }
783
- *
784
- * // Resolve the current user and expose it as `ctx.user` downstream.
785
- * const auth = middleware<{ user: User }>(async ({ next }) => {
786
- * const user = await getCurrentUser();
787
- * if (!user) {
788
- * throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
789
- * }
790
- * await next({ user });
791
- * });
792
- *
793
- * // Create a trace id for this command run and expose it as `ctx.traceId`.
794
- * const telemetry = middleware<{ traceId: string }>(async ({ meta, next }) => {
795
- * const traceId = startTrace(`${meta.name}.${meta.command}`);
796
- * await next({ traceId });
797
- * });
798
- *
799
- * command('deploy')
800
- * .middleware(auth) // C becomes { user: User }
801
- * .middleware(telemetry) // C becomes { user: User } & { traceId: string }
802
- * .action(({ ctx }) => {
803
- * ctx.user; // User — typed
804
- * ctx.traceId; // string — typed
805
- * });
806
- * ```
807
- *
808
- * @param m - {@link Middleware} instance created via {@linkcode middleware | middleware()}.
809
- * Middleware handlers receive `{ args, flags, ctx, out, meta, next }`.
810
- * @returns The builder (for chaining).
811
- */
812
- middleware<Output extends Record<string, unknown>>(m: Middleware<Output>): CommandBuilder<F, A, WidenContext<C, Output>>;
813
- /**
814
- * Set the command's description for help text.
815
- *
816
- * Displayed below the usage line in `--help` output and next to the
817
- * command name in parent command/group help listings.
818
- *
819
- * @param text - One-line description of what the command does.
820
- *
821
- * @example
822
- * ```ts
823
- * command('deploy')
824
- * .description('Deploy the application to a target environment')
825
- * .action(({ out }) => { out.log('deploying...'); });
826
- *
827
- * // $ mycli deploy --help
828
- * // Usage: deploy [flags]
829
- * //
830
- * // Deploy the application to a target environment
831
- * ```
832
- *
833
- * @returns The builder (for chaining).
834
- */
835
- description(text: string): CommandBuilder<F, A, C>;
836
- /**
837
- * Add an alternative name for this command.
838
- *
839
- * Aliases are accepted during dispatch alongside the primary name.
840
- * Multiple aliases can be chained. Aliases are shown in help output.
841
- *
842
- * @param name - Alternative command name (e.g. `'d'` for `deploy`).
843
- *
844
- * @example
845
- * ```ts
846
- * command('deploy')
847
- * .alias('d')
848
- * .alias('push')
849
- * .action(({ out }) => { out.log('deploying...'); });
850
- *
851
- * // All equivalent:
852
- * // $ mycli deploy
853
- * // $ mycli d
854
- * // $ mycli push
855
- * ```
856
- *
857
- * @returns The builder (for chaining).
858
- */
859
- alias(name: string): CommandBuilder<F, A, C>;
860
- /**
861
- * Hide this command from help listings.
862
- *
863
- * The command remains fully functional and dispatchable — it just
864
- * won't appear in `--help` output or shell completions. Useful for
865
- * internal/debug commands.
866
- *
867
- * @example
868
- * ```ts
869
- * command('debug-dump')
870
- * .hidden()
871
- * .action(({ out }) => { out.log(JSON.stringify(internalState)); });
872
- *
873
- * // $ mycli --help → 'debug-dump' is not listed
874
- * // $ mycli debug-dump → still works
875
- * ```
876
- *
877
- * @returns The builder (for chaining).
878
- */
879
- hidden(): CommandBuilder<F, A, C>;
880
- /**
881
- * Add a usage example to help text.
882
- *
883
- * Examples are rendered in the "Examples:" section of `--help` output.
884
- * Call multiple times to add several examples. Each example shows a
885
- * shell invocation, optionally with a description.
886
- *
887
- * `cmd` may be a literal string or a function receiving the program
888
- * {@link ExampleMeta} (`name`, `version`), resolved at render time. Use the
889
- * function form to reference the invoked program name instead of hardcoding
890
- * it, so examples stay truthful under symlinks, `inheritName`, and
891
- * `npx x` vs a global install.
892
- *
893
- * @param cmd - The example command line, or a `(meta) => string` builder.
894
- * @param description - Optional one-line explanation of what the example does.
895
- *
896
- * @example
897
- * ```ts
898
- * command('deploy')
899
- * .arg('target', arg.string())
900
- * .flag('force', flag.boolean().alias('f'))
901
- * .example('deploy production', 'Deploy to production')
902
- * .example((m) => `${m.name} deploy staging -f`, 'Force deploy to staging')
903
- * .action(({ args, flags }) => { ... });
904
- *
905
- * // $ mycli deploy --help
906
- * // ...
907
- * // Examples:
908
- * // deploy production Deploy to production
909
- * // mycli deploy staging -f Force deploy to staging
910
- * ```
911
- *
912
- * @returns The builder (for chaining).
913
- */
914
- example(cmd: ExampleCommand, description?: string): CommandBuilder<F, A, C>;
915
- /**
916
- * Register a named flag on this command.
917
- *
918
- * The flag name is added to the type-level `F` map. Duplicate flag names
919
- * are prevented at the type level via the `Exclude` constraint.
920
- *
921
- * The builder controls the flag's type, presence, aliases, env/config
922
- * bindings, and description. See {@link FlagBuilder} for available modifiers.
923
- *
924
- * @param name - Flag name: the `--name` CLI token and the matching key on `flags`
925
- * in the handler. The name is preserved as-is (no camelCasing); read non-identifier
926
- * names such as `'dry-run'` with bracket access (`flags['dry-run']`).
927
- * @param builder - Configured {@linkcode FlagBuilder} from {@linkcode flag | flag.string()},
928
- * `flag.boolean()`, `flag.number()`, `flag.enum()`, `flag.array()`, or `flag.custom()`.
929
- *
930
- * @example
931
- * ```ts
932
- * command('serve')
933
- * .flag('port', flag.number()
934
- * .alias('p')
935
- * .env('PORT')
936
- * .default(3000)
937
- * .describe('Port to listen on'))
938
- * .flag('host', flag.string()
939
- * .env('HOST')
940
- * .default('localhost')
941
- * .describe('Bind address'))
942
- * .flag('verbose', flag.boolean()
943
- * .alias('v')
944
- * .describe('Enable verbose logging'))
945
- * .action(({ flags, out }) => {
946
- * flags.port; // number
947
- * flags.host; // string
948
- * flags.verbose; // boolean
949
- * out.log(`Listening on ${flags.host}:${flags.port}`);
950
- * });
951
- *
952
- * // $ mycli serve --port 8080 -v
953
- * // $ PORT=9090 mycli serve
954
- * ```
955
- *
956
- * @returns The builder (for chaining).
957
- * @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
958
- * which a plain record cannot carry.
959
- * @throws {@link CLIError} `FLAG_NAME_COLLISION` when the command already
960
- * declares this name, or the new flag's spellings collide with another
961
- * flag's.
962
- * @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling
963
- * collides with one propagated to a registered subcommand.
964
- */
965
- flag<N extends string, B extends FlagBuilder<FlagConfig>>(name: N & Exclude<N, keyof F>, builder: B): CommandBuilder<F & Record<N, B>, A, C>;
966
- /**
967
- * Register a named positional argument on this command.
968
- *
969
- * Args are ordered by registration — position on the CLI matches the
970
- * order of `.arg()` calls. The arg name is added to the type-level `A`
971
- * map. Duplicate arg names are prevented at the type level via the
972
- * `Exclude` constraint.
973
- *
974
- * The builder controls the arg's type, presence, env binding, and
975
- * description. See {@link ArgBuilder} for available modifiers.
976
- *
977
- * @param name - Positional arg name (used in help text and `args.*`).
978
- * @param builder - Configured {@linkcode ArgBuilder} from `arg.string()`, `arg.number()`,
979
- * or `arg.custom()`.
980
- *
981
- * @example
982
- * ```ts
983
- * command('deploy')
984
- * // Required string arg — first positional
985
- * .arg('target', arg.string()
986
- * .env('DEPLOY_TARGET')
987
- * .describe('Deploy target'))
988
- * // Optional number arg — second positional
989
- * .arg('port', arg.number()
990
- * .env('PORT')
991
- * .default(3000)
992
- * .describe('Port number'))
993
- * .action(({ args }) => {
994
- * args.target; // string
995
- * args.port; // number
996
- * });
997
- *
998
- * // Usage: deploy [flags] <target> [port]
999
- * // $ mycli deploy production 8080
1000
- * // $ DEPLOY_TARGET=staging mycli deploy
1001
- * ```
1002
- *
1003
- * @returns The builder (for chaining).
1004
- * @throws {@link CLIError} `INVALID_SCHEMA` when the name is `__proto__`,
1005
- * which a plain record cannot carry.
1006
- * @throws {@link CLIError} `INVALID_BUILDER_STATE` when an earlier arg on this
1007
- * command is variadic, so this one could never be filled.
1008
- * @throws {@link CLIError} `DUPLICATE_STDIN_INPUT` when another input on this
1009
- * command already consumes stdin exclusively.
1010
- */
1011
- arg<N extends string, B extends ArgBuilder<ArgConfig>>(name: N & Exclude<N, keyof A>, builder: B): CommandBuilder<F, A & Record<N, B>, C>;
1012
- /**
1013
- * Register a nested subcommand on this command.
1014
- *
1015
- * The subcommand's builder is stored in `_subcommands` for the CLI layer's
1016
- * `compileCommand()` to traverse when building the execution graph. The
1017
- * subcommand's `CommandSchema` is also appended to `schema.commands` for
1018
- * help rendering and completion generation.
1019
- *
1020
- * Does not change `F`, `A`, or `C` — subcommands are type-erased at the
1021
- * parent level (same semantics as `CLIBuilder.command()`). The handler is
1022
- * preserved.
1023
- *
1024
- * @example
1025
- * ```ts
1026
- * const db = group('db')
1027
- * .description('Database operations')
1028
- * .command(migrateCmd)
1029
- * .command(seedCmd);
1030
- * ```
1031
- *
1032
- * @param sub - Child {@link CommandBuilder} to nest under this command.
1033
- * @returns The builder (for chaining).
1034
- * @throws {@link CLIError} `PROPAGATED_FLAG_COLLISION` when a spelling this
1035
- * command propagates collides with one the subcommand, or any of its own
1036
- * descendants, declares.
1037
- */
1038
- 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>;
1039
- /**
1040
- * Register the action handler for this command.
1041
- *
1042
- * The handler receives fully typed `{ args, flags, ctx, out, meta }` derived
1043
- * from the accumulated `.flag()`, `.arg()`, `.derive()`, and `.middleware()`
1044
- * definitions.
1045
- *
1046
- * May be synchronous or async. Return values are ignored; command handlers
1047
- * communicate through `out`, thrown errors, and side effects.
1048
- *
1049
- * @param handler - Function receiving `ActionParams<F, A, C>`.
1050
- *
1051
- * @example
1052
- * ```ts
1053
- * // Minimal
1054
- * command('greet')
1055
- * .arg('name', arg.string())
1056
- * .action(({ args, out }) => {
1057
- * out.log(`Hello, ${args.name}!`);
1058
- * });
1059
- * ```
1060
- *
1061
- * @example
1062
- * ```ts
1063
- * // Full params — flags, args, context, output, metadata
1064
- * command('deploy')
1065
- * .arg('target', arg.string().env('DEPLOY_TARGET'))
1066
- * .flag('force', flag.boolean().alias('f'))
1067
- * .flag('region', flag.enum(['us', 'eu', 'ap']).env('REGION'))
1068
- * .middleware(auth)
1069
- * .action(async ({ args, flags, ctx, out, meta }) => {
1070
- * args.target; // string
1071
- * flags.force; // boolean
1072
- * flags.region; // 'us' | 'eu' | 'ap' | undefined
1073
- * ctx.user; // User (from auth middleware)
1074
- * meta.command; // string
1075
- *
1076
- * const spinner = out.spinner('Deploying...');
1077
- * await deploy(args.target, { force: flags.force });
1078
- * spinner.stop();
1079
- * out.log('Done');
1080
- * });
1081
- * ```
1082
- *
1083
- * @returns The builder (for chaining).
1084
- */
1085
- action(handler: ActionHandler<F, A, C>): CommandBuilder<F, A, C>;
1086
- }
1087
- /**
1088
- * Create a new command builder.
1089
- *
1090
- * @param name - The command name used for dispatch (e.g. `'deploy'`).
1091
- *
1092
- * @example
1093
- * ```ts
1094
- * import { arg, command, flag } from '@kjanat/dreamcli';
1095
- *
1096
- * const greet = command('greet')
1097
- * .arg('name', arg.string())
1098
- * .flag('loud', flag.boolean())
1099
- * .action(({ args, flags, out }) => {
1100
- * const msg = `Hello, ${args.name}!`;
1101
- * out.log(flags.loud ? msg.toUpperCase() : msg);
1102
- * });
1103
- * ```
1104
- *
1105
- * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
1106
- */
1107
- declare function command(name: string): CommandBuilder;
1108
- /**
1109
- * Create a command builder intended for use as a command group.
1110
- *
1111
- * Semantically identical to {@linkcode command | command()} — a group is simply a command that
1112
- * has subcommands registered via `.command()`. The separate factory
1113
- * communicates intent: groups organise subcommands, leaf commands have actions.
1114
- *
1115
- * A group may also have its own `.action()` (e.g. `git remote` lists remotes
1116
- * when invoked without a subcommand, but dispatches to `git remote add`, etc.).
1117
- *
1118
- * @param name - The group name used for dispatch (e.g. `'db'`).
1119
- *
1120
- * @example
1121
- * ```ts
1122
- * const db = group('db')
1123
- * .description('Database operations')
1124
- * .command(migrateCmd)
1125
- * .command(seedCmd);
1126
- * ```
1127
- *
1128
- * @returns A fresh {@link CommandBuilder} with empty flags, args, and context.
1129
- */
1130
- declare function group(name: string): CommandBuilder;
1131
- //#endregion
1132
- export { type ActionHandler, type ActionParams, type AnyCommandBuilder, type CommandArgEntry, type CommandArgEntryDefinition, CommandBuilder, type CommandDefinition, type CommandExample, type CommandMeta, type CommandSchema, type DeriveHandler, type DeriveParams, type ErasedActionHandler, type ErasedDeriveHandler, type ErasedInputSources, type ErasedInteractiveResolver, type ExampleCommand, type ExampleMeta, type ExecutionStep, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Out, type RunnableCommand, type WidenContext, type WidenDerivedContext, command, createCommandSchema, group, outBrand, resolveExampleCommand };