@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
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * CLI entry point builder with command registration and dispatch.
3
3
  *
4
- * The `cli()` factory returns an immutable `CLIBuilder` that registers
4
+ * The {@linkcode cli | cli()} factory returns an immutable {@linkcode CLIBuilder} that registers
5
5
  * commands, handles `--help`/`--version` at root level, dispatches to
6
6
  * the matched command, and provides both a testable `.execute()` path
7
7
  * and a production `.run()` path.
@@ -12,19 +12,16 @@
12
12
  import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
13
  import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
14
14
  import type { FormatLoader } from '#internals/core/config/index.ts';
15
- import { discoverConfig } from '#internals/core/config/index.ts';
16
- import { discoverPackageJson, inferCliName } from '#internals/core/config/package-json.ts';
17
- import { CLIError, ParseError } from '#internals/core/errors/index.ts';
15
+ import { CLIError } from '#internals/core/errors/index.ts';
16
+ import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
18
17
  import type { HelpOptions } from '#internals/core/help/index.ts';
19
18
  import { formatHelp } from '#internals/core/help/index.ts';
20
- import type { CapturedOutput, Verbosity } from '#internals/core/output/index.ts';
19
+ import type { CapturedOutput } from '#internals/core/output/index.ts';
21
20
  import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
22
- import { parse } from '#internals/core/parse/index.ts';
23
- import type { PromptEngine, TestAnswer } from '#internals/core/prompt/index.ts';
24
- import { createTerminalPrompter } from '#internals/core/prompt/index.ts';
25
21
  import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
26
22
  import { arg } from '#internals/core/schema/arg.ts';
27
23
  import type {
24
+ AnyCommandBuilder,
28
25
  CommandBuilder,
29
26
  CommandMeta,
30
27
  CommandSchema,
@@ -37,20 +34,73 @@ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
37
34
  import { runCommand } from '#internals/core/testkit/index.ts';
38
35
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
39
36
  import { createAdapter } from '#internals/runtime/auto.ts';
40
- import { dispatch, findClosestCommand } from './dispatch.ts';
37
+ import type { OutputPolicy } from './planner.ts';
38
+ import { planInvocation } from './planner.ts';
41
39
  import type { CLIPlugin } from './plugin.ts';
42
40
  import { plugin } from './plugin.ts';
43
- import { collectPropagatedFlags } from './propagate.ts';
44
41
  import { formatRootHelp } from './root-help.ts';
42
+ import { prepareRuntimePreflight } from './runtime-preflight.ts';
45
43
 
46
44
  // --- Type-erased command — erasure function (interface now in schema/command.ts)
47
45
 
46
+ function commandRoutes(schema: CommandSchema): readonly string[] {
47
+ return [schema.name, ...schema.aliases];
48
+ }
49
+
50
+ function assertNoSiblingRouteConflict(
51
+ parentCommandName: string,
52
+ routeOwners: Map<string, string>,
53
+ route: string,
54
+ commandName: string,
55
+ ): void {
56
+ const owner = routeOwners.get(route);
57
+ if (owner !== undefined) {
58
+ throw new CLIError(
59
+ `Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`,
60
+ {
61
+ code: 'DUPLICATE_COMMAND',
62
+ suggest: 'Ensure sibling command names and aliases are unique',
63
+ },
64
+ );
65
+ }
66
+
67
+ routeOwners.set(route, commandName);
68
+ }
69
+
70
+ function assertNoTopLevelRouteConflict(
71
+ commands: readonly ErasedCommand[],
72
+ incoming: CommandSchema,
73
+ ): void {
74
+ const routeOwners = new Map<string, string>();
75
+
76
+ for (const command of commands) {
77
+ for (const route of commandRoutes(command.schema)) {
78
+ assertNoSiblingRouteConflict('root', routeOwners, route, command.schema.name);
79
+ }
80
+ }
81
+
82
+ for (const route of commandRoutes(incoming)) {
83
+ const owner = routeOwners.get(route);
84
+ if (owner !== undefined) {
85
+ throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
86
+ code: 'DUPLICATE_COMMAND',
87
+ suggest:
88
+ owner === incoming.name
89
+ ? `Ensure command '${incoming.name}' does not reuse route '${route}'`
90
+ : `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`,
91
+ });
92
+ }
93
+
94
+ routeOwners.set(route, incoming.name);
95
+ }
96
+ }
97
+
48
98
  /**
49
- * Erase a typed CommandBuilder into an ErasedCommand, recursively
99
+ * Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
50
100
  * building the subcommand tree.
51
101
  *
52
- * The closure captures the fully-typed builder, so `runCommand()` receives
53
- * the original `CommandBuilder<F, A>` — no type assertions needed.
102
+ * The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
103
+ * the original `CommandBuilder<F, A>` — no type assertions needed.\
54
104
  * Subcommands are recursively erased and indexed by name and alias for
55
105
  * O(1) lookup during dispatch.
56
106
  *
@@ -63,17 +113,23 @@ function eraseCommand<
63
113
  >(cmd: CommandBuilder<F, A, C>): ErasedCommand {
64
114
  // Recursively erase subcommands, keyed by name and alias.
65
115
  const subcommands = new Map<string, ErasedCommand>();
116
+ const routeOwners = new Map<string, string>();
66
117
  for (const sub of cmd._subcommands) {
118
+ const routes = commandRoutes(sub.schema);
119
+ for (const route of routes) {
120
+ assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
121
+ }
122
+
67
123
  const erased = eraseCommand(sub);
68
- subcommands.set(sub.schema.name, erased);
69
- for (const alias of sub.schema.aliases) {
70
- subcommands.set(alias, erased);
124
+ for (const route of routes) {
125
+ subcommands.set(route, erased);
71
126
  }
72
127
  }
73
128
 
74
129
  return {
75
130
  schema: cmd.schema,
76
131
  subcommands,
132
+ _command: cmd as unknown as AnyCommandBuilder,
77
133
  _execute(argv, options) {
78
134
  return runCommand(cmd, argv, options);
79
135
  },
@@ -85,8 +141,8 @@ function eraseCommand<
85
141
  /**
86
142
  * Runtime descriptor for the CLI program.
87
143
  *
88
- * Stores the program name, version, description, and registered commands.
89
- * Built incrementally by `CLIBuilder`.
144
+ * Stores the program name, version, description, and registered commands.\
145
+ * Built incrementally by {@linkcode CLIBuilder}.
90
146
  */
91
147
  interface CLISchema {
92
148
  /** Program name (used in help text, usage lines, and completion scripts). */
@@ -110,23 +166,26 @@ interface CLISchema {
110
166
  * dispatch by name as usual, but empty argv or flags-only argv falls
111
167
  * through to this command instead of showing root help.
112
168
  *
113
- * Set via the `.default()` builder method.
169
+ * Set via the {@linkcode CLIBuilder.default | .default()} builder method.
114
170
  */
115
171
  readonly defaultCommand: ErasedCommand | undefined;
116
172
  /**
117
- * Config discovery settings. When defined, `.run()` auto-discovers and
118
- * loads a config file before command dispatch.
173
+ * Config discovery settings.
174
+ *
175
+ * When defined, {@linkcode CLIBuilder.run | .run()} auto-discovers and loads a config file before command dispatch.
119
176
  *
120
- * Set via the `.config()` builder method.
177
+ * Set via the {@linkcode CLIBuilder.config | .config()} builder method.
121
178
  */
122
179
  readonly configSettings: ConfigSettings | undefined;
123
180
  /**
124
181
  * Package.json auto-discovery settings. When defined, `.run()` discovers
125
182
  * the nearest `package.json` and merges metadata before dispatch.
126
183
  *
127
- * Set via the `.packageJson()` builder method.
184
+ * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
128
185
  */
129
186
  readonly packageJsonSettings: PackageJsonSettings | undefined;
187
+ /** Whether built-in `.completions()` command registration is active. */
188
+ readonly hasBuiltInCompletions: boolean;
130
189
  /** Registered CLI plugins. */
131
190
  readonly plugins: readonly CLIPlugin[];
132
191
  }
@@ -134,8 +193,8 @@ interface CLISchema {
134
193
  /**
135
194
  * Config discovery settings for automatic config file loading.
136
195
  *
137
- * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
138
- * call {@link discoverConfig} before dispatching to a command.
196
+ * Stored in {@link CLISchema} and consumed by {@linkcode CLIBuilder.run()} to call
197
+ * {@link discoverConfig} before dispatching to a command.
139
198
  */
140
199
  interface ConfigSettings {
141
200
  /**
@@ -174,19 +233,12 @@ interface PackageJsonSettings {
174
233
  // --- Options for execute/run
175
234
 
176
235
  /**
177
- * Options for `CLIBuilder.execute()` and `CLIBuilder.run()`.
236
+ * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
178
237
  *
179
- * Mirrors `RunOptions` from testkit but adds CLI-level concerns
180
- * (version display, root help formatting, runtime adapter).
238
+ * Derives from {@linkcode RunOptions} while excluding command-execution internals
239
+ * (`meta`, `mergedSchema`) and adding the CLI-level runtime adapter.
181
240
  */
182
- interface CLIRunOptions {
183
- /**
184
- * CLI plugins to apply for this execution.
185
- *
186
- * @internal — populated from `CLIBuilder.schema.plugins` during dispatch.
187
- */
188
- readonly plugins?: readonly CLIPlugin[];
189
-
241
+ interface CLIRunOptions extends Omit<RunOptions, 'meta' | 'mergedSchema'> {
190
242
  /**
191
243
  * Runtime adapter providing platform-specific I/O, argv, env, etc.
192
244
  *
@@ -194,183 +246,18 @@ interface CLIRunOptions {
194
246
  * Ignored by `.execute()` (which is process-free by design).
195
247
  */
196
248
  readonly adapter?: RuntimeAdapter;
197
-
198
- /**
199
- * Environment variables for flag resolution.
200
- *
201
- * Flags with `.env('VAR')` configured resolve from this record
202
- * when no CLI value is provided (CLI → env → config → default).
203
- */
204
- readonly env?: Readonly<Record<string, string | undefined>>;
205
-
206
- /**
207
- * Configuration object for flag resolution.
208
- *
209
- * Flags with `.config('path')` configured resolve from this record
210
- * when no CLI or env value is provided (CLI → env → config → prompt → default).
211
- * Config is plain JSON — file loading is the caller's responsibility.
212
- */
213
- readonly config?: Readonly<Record<string, unknown>>;
214
-
215
- /**
216
- * Full stdin contents for args configured with `.stdin()`.
217
- *
218
- * `run()` populates this from `adapter.readStdin()` only when the selected
219
- * invocation needs stdin. `execute()` accepts it directly so tests can
220
- * simulate piped input without a runtime adapter.
221
- */
222
- readonly stdinData?: string | null;
223
-
224
- /**
225
- * Prompt engine for interactive flag resolution.
226
- *
227
- * When provided, flags with `.prompt()` configured that have no value
228
- * after CLI/env/config resolution will be prompted interactively.
229
- * When absent (and `answers` is also absent), prompting is skipped.
230
- *
231
- * Takes precedence over `answers` when both are provided.
232
- */
233
- readonly prompter?: PromptEngine;
234
-
235
- /**
236
- * Pre-configured prompt answers for testing convenience.
237
- *
238
- * When provided, a test prompter is created from these answers via
239
- * `createTestPrompter(answers)`. Each entry is consumed in order —
240
- * use `PROMPT_CANCEL` to simulate cancellation.
241
- *
242
- * Ignored when an explicit `prompter` is provided.
243
- */
244
- readonly answers?: readonly TestAnswer[];
245
-
246
- /**
247
- * Verbosity level for the output channel.
248
- * @defaultValue `'normal'`
249
- */
250
- readonly verbosity?: Verbosity;
251
-
252
- /**
253
- * Enable JSON output mode.
254
- *
255
- * When `true`, `log` and `info` messages are redirected to stderr
256
- * so that stdout is reserved exclusively for structured `json()` output.
257
- * Errors are also rendered as JSON to stderr.
258
- *
259
- * @defaultValue `false`
260
- */
261
- readonly jsonMode?: boolean;
262
-
263
- /**
264
- * Whether stdout is connected to a TTY.
265
- *
266
- * When provided, propagated to the output channel's `isTTY` field.
267
- * In `.run()`, automatically sourced from `adapter.isTTY` when not
268
- * explicitly set.
269
- *
270
- * @defaultValue `false`
271
- */
272
- readonly isTTY?: boolean;
273
-
274
- /**
275
- * Output channel override used by `run()` for live terminal rendering.
276
- *
277
- * @internal — `execute()` remains capture-first by default.
278
- */
279
- readonly out?: Out;
280
-
281
- /**
282
- * Capture buffers paired with `out`.
283
- *
284
- * @internal — `run()` omits this and accepts empty buffers in the returned
285
- * `RunResult` because output is already written to the real adapter streams.
286
- */
287
- readonly captured?: CapturedOutput;
288
-
289
- /**
290
- * Help formatting options (width, binName).
291
- * `binName` defaults to the CLI program name.
292
- */
293
- readonly help?: HelpOptions;
294
- }
295
-
296
- // --- --config flag extraction
297
-
298
- /**
299
- * Extract `--config <path>` or `--config=<path>` from argv.
300
- *
301
- * Returns the config path (if present) and the filtered argv with the
302
- * flag (and its value) removed. Bare `--config` at end of argv (no value)
303
- * and `--config=` (empty value) are silently ignored (treated as absent).
304
- *
305
- * The `--config=<path>` form is checked first so that a bare `--config`
306
- * token does not consume the next element when an equals-form is present.
307
- *
308
- * @param argv - Raw argument vector to scan for `--config`.
309
- * @returns The extracted config path and filtered argv with the flag removed.
310
- *
311
- * @internal
312
- */
313
- function extractConfigFlag(argv: readonly string[]): {
314
- readonly configPath: string | undefined;
315
- readonly filteredArgv: readonly string[];
316
- } {
317
- // --- equals form: --config=<path> ---
318
- const eqIdx = argv.findIndex((arg) => arg.startsWith('--config='));
319
- if (eqIdx !== -1) {
320
- const value = (argv[eqIdx] as string).slice('--config='.length);
321
- // Always strip the element; empty value (--config=) treated as absent.
322
- const filteredArgv = [...argv.slice(0, eqIdx), ...argv.slice(eqIdx + 1)];
323
- return {
324
- configPath: value.length > 0 ? value : undefined,
325
- filteredArgv,
326
- };
327
- }
328
-
329
- // --- space-separated form: --config <path> ---
330
- const idx = argv.indexOf('--config');
331
- const nextArg = idx >= 0 ? argv[idx + 1] : undefined;
332
- if (idx === -1 || nextArg === undefined) {
333
- return { configPath: undefined, filteredArgv: argv };
334
- }
335
- const filteredArgv = [...argv.slice(0, idx), ...argv.slice(idx + 2)];
336
- return { configPath: nextArg, filteredArgv };
337
- }
338
-
339
- // --- CLI → CommandMeta builder
340
-
341
- /**
342
- * Build {@link CommandMeta} from CLI-level schema and the leaf command name.
343
- *
344
- * @param cliSchema - Root CLI schema providing program name and version.
345
- * @param helpOptions - Help formatting options; `binName` overrides the program name when set.
346
- * @param commandName - Name of the matched leaf command.
347
- * @returns Metadata record consumed by command actions and help formatters.
348
- *
349
- * @internal
350
- */
351
- function buildMeta(
352
- cliSchema: CLISchema,
353
- helpOptions: HelpOptions,
354
- commandName: string,
355
- ): CommandMeta {
356
- return {
357
- name: cliSchema.name,
358
- bin: helpOptions.binName ?? cliSchema.name,
359
- version: cliSchema.version,
360
- command: commandName,
361
- };
362
249
  }
363
250
 
364
251
  // --- Command run options builder
365
252
 
366
253
  /**
367
- * Build `RunOptions` from `CLIRunOptions`, conditionally spreading each
254
+ * Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
368
255
  * field to satisfy `exactOptionalPropertyTypes`.
369
256
  *
370
257
  * @param options - CLI-level run options (may be `undefined` for defaults).
371
258
  * @param helpOptions - Help formatting options forwarded to commands.
372
259
  * @param meta - Optional command metadata (omitted for root-level dispatch).
373
- * @returns Options record ready for `ErasedCommand._execute()`.
260
+ * @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
374
261
  *
375
262
  * @internal
376
263
  */
@@ -396,129 +283,6 @@ function buildCommandRunOptions(
396
283
  };
397
284
  }
398
285
 
399
- /**
400
- * Index commands by name and alias for O(1) dispatch lookup.
401
- *
402
- * @param commands - Registered top-level commands.
403
- * @returns Map keyed by command name and every alias.
404
- *
405
- * @internal
406
- */
407
- function buildRootCommandMap(
408
- commands: readonly ErasedCommand[],
409
- ): ReadonlyMap<string, ErasedCommand> {
410
- const rootCommands = new Map<string, ErasedCommand>();
411
- for (const cmd of commands) {
412
- rootCommands.set(cmd.schema.name, cmd);
413
- for (const alias of cmd.schema.aliases) {
414
- rootCommands.set(alias, cmd);
415
- }
416
- }
417
- return rootCommands;
418
- }
419
-
420
- /**
421
- * Check whether a single command's args require stdin for the given argv.
422
- *
423
- * @param schema - Command schema whose args are inspected for `.stdin()` configuration.
424
- * @param argv - Remaining argv tokens after dispatch (excludes the command name).
425
- * @returns `true` when at least one arg has `stdinMode` and its parsed value is absent or `'-'`.
426
- *
427
- * @internal
428
- */
429
- function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean {
430
- if (argv.includes('--help') || argv.includes('-h')) {
431
- return false;
432
- }
433
-
434
- try {
435
- const parsed = parse(schema, argv);
436
- return schema.args.some(({ name, schema: argSchema }) => {
437
- const parsedValue = parsed.args[name];
438
- return argSchema.stdinMode && (parsedValue === undefined || parsedValue === '-');
439
- });
440
- } catch (err: unknown) {
441
- if (err instanceof ParseError) {
442
- return false;
443
- }
444
- throw err;
445
- }
446
- }
447
-
448
- /**
449
- * Determine whether the full CLI invocation will need stdin data.
450
- *
451
- * Dispatches argv through the command tree to find the target command,
452
- * then delegates to {@link commandInvocationNeedsStdin}. Short-circuits
453
- * to `false` for `--help`, `--version`, virtual `help`, and empty argv
454
- * without a default command.
455
- *
456
- * @param builder - CLI builder whose schema and command tree are inspected.
457
- * @param argv - Raw argv tokens (after `--json` stripping).
458
- * @returns `true` when the resolved command has args that require stdin.
459
- *
460
- * @internal
461
- */
462
- function invocationNeedsStdin(builder: CLIBuilder, argv: readonly string[]): boolean {
463
- const filteredArgv = argv.includes('--json') ? argv.filter((arg) => arg !== '--json') : argv;
464
-
465
- if (filteredArgv.includes('--version') || filteredArgv.includes('-V')) {
466
- return false;
467
- }
468
- if (filteredArgv.includes('--help') || filteredArgv.includes('-h')) {
469
- return false;
470
- }
471
-
472
- const firstArg = filteredArgv[0];
473
- if (firstArg === 'help') {
474
- const hasRealHelpCommand = builder.schema.commands.some(
475
- (command) => command.schema.name === 'help' || command.schema.aliases.includes('help'),
476
- );
477
- if (!hasRealHelpCommand) {
478
- return false;
479
- }
480
- }
481
-
482
- if (firstArg === undefined && builder.schema.defaultCommand === undefined) {
483
- return false;
484
- }
485
- if (builder.schema.commands.length === 0) {
486
- return false;
487
- }
488
-
489
- const rootCommands = buildRootCommandMap(builder.schema.commands);
490
- const result = dispatch(filteredArgv, rootCommands);
491
- const defaultCommand = builder.schema.defaultCommand;
492
-
493
- switch (result.kind) {
494
- case 'unknown': {
495
- if (defaultCommand !== undefined && result.parentPath.length === 0) {
496
- const suggestion =
497
- result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
498
- if (suggestion === undefined) {
499
- return commandInvocationNeedsStdin(defaultCommand.schema, filteredArgv);
500
- }
501
- }
502
- return false;
503
- }
504
-
505
- case 'needs-subcommand':
506
- return false;
507
-
508
- case 'match': {
509
- const propagated = collectPropagatedFlags(result.commandPath);
510
- const mergedSchema =
511
- Object.keys(propagated).length > 0
512
- ? {
513
- ...result.command.schema,
514
- flags: { ...propagated, ...result.command.schema.flags },
515
- }
516
- : result.command.schema;
517
- return commandInvocationNeedsStdin(mergedSchema, result.remainingArgv);
518
- }
519
- }
520
- }
521
-
522
286
  // --- CLIBuilder — immutable builder for the CLI program
523
287
 
524
288
  /**
@@ -528,12 +292,12 @@ function invocationNeedsStdin(builder: CLIBuilder, argv: readonly string[]): boo
528
292
  * dispatches to the matched command based on argv.
529
293
  *
530
294
  * Two execution paths:
531
- * - `.execute(argv, options?)` — testable, returns `RunResult`
295
+ * - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
532
296
  * - `.run(options?)` — production entry, reads `process.argv`, exits process
533
297
  *
534
298
  * @example
535
299
  * ```ts
536
- * import { cli, command, flag, arg } from 'dreamcli';
300
+ * import { cli, command, flag, arg } from '@kjanat/dreamcli';
537
301
  *
538
302
  * const deploy = command('deploy')
539
303
  * .arg('target', arg.string())
@@ -552,6 +316,7 @@ class CLIBuilder {
552
316
  /** @internal Runtime schema descriptor. */
553
317
  readonly schema: CLISchema;
554
318
 
319
+ /** Build a CLIBuilder from a pre-constructed schema descriptor. */
555
320
  constructor(schema: CLISchema) {
556
321
  this.schema = schema;
557
322
  }
@@ -625,7 +390,7 @@ class CLIBuilder {
625
390
  *
626
391
  * @example Bun built-in parsers
627
392
  * ```ts
628
- * import { configFormat } from 'dreamcli';
393
+ * import { configFormat } from '@kjanat/dreamcli';
629
394
  *
630
395
  * cli('myapp')
631
396
  * .config('myapp')
@@ -636,7 +401,7 @@ class CLIBuilder {
636
401
  *
637
402
  * @example npm package parsers
638
403
  * ```ts
639
- * import { configFormat } from 'dreamcli';
404
+ * import { configFormat } from '@kjanat/dreamcli';
640
405
  * import { parse as parseYaml } from 'yaml';
641
406
  * import { parse as parseTOML } from '@iarna/toml';
642
407
  *
@@ -714,7 +479,7 @@ class CLIBuilder {
714
479
  *
715
480
  * The command's type parameters are erased for heterogeneous storage.
716
481
  * Type safety is preserved inside the closure that delegates to
717
- * `runCommand()`.
482
+ * {@linkcode runCommand | runCommand()}.
718
483
  *
719
484
  * @param cmd - {@link CommandBuilder} to register.
720
485
  * @returns The builder (for chaining).
@@ -724,6 +489,8 @@ class CLIBuilder {
724
489
  A extends Record<string, ArgBuilder<ArgConfig>>,
725
490
  C extends Record<string, unknown>,
726
491
  >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
492
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
493
+
727
494
  return new CLIBuilder({
728
495
  ...this.schema,
729
496
  commands: [...this.schema.commands, eraseCommand(cmd)],
@@ -771,12 +538,9 @@ class CLIBuilder {
771
538
  suggest: 'Call .default() only once when building the CLI',
772
539
  });
773
540
  }
774
- if (this.schema.commands.some((c) => c.schema.name === cmd.schema.name)) {
775
- throw new CLIError(`Command '${cmd.schema.name}' is already registered`, {
776
- code: 'DUPLICATE_COMMAND',
777
- suggest: 'Use .default() instead of .command() to register the default command',
778
- });
779
- }
541
+
542
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
543
+
780
544
  const erased = eraseCommand(cmd);
781
545
  return new CLIBuilder({
782
546
  ...this.schema,
@@ -810,7 +574,7 @@ class CLIBuilder {
810
574
  *
811
575
  * The generated command accepts a `--shell` flag (required, enum of
812
576
  * all {@link Shell} values) and writes the completion script to stdout
813
- * via `out.log()`. Unsupported shells throw a descriptive `CLIError`
577
+ * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
814
578
  * instead of a generic parse error.
815
579
  *
816
580
  * Call this **after** registering all other commands so the completion
@@ -830,7 +594,7 @@ class CLIBuilder {
830
594
  * ```
831
595
  */
832
596
  completions(options?: CompletionOptions): CLIBuilder {
833
- if (this.schema.commands.some((c) => c.schema.name === 'completions')) {
597
+ if (this.schema.hasBuiltInCompletions) {
834
598
  throw new CLIError('.completions() has already been called', {
835
599
  code: 'DUPLICATE_COMMAND',
836
600
  suggest: 'Call .completions() only once when building the CLI',
@@ -846,6 +610,7 @@ class CLIBuilder {
846
610
  // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
847
611
  const shellMap = new Map<string, Shell>();
848
612
  for (const s of SHELLS) shellMap.set(s, s);
613
+ shellMap.set('pwsh', 'powershell');
849
614
 
850
615
  const cmd = command('completions')
851
616
  .alias('completion')
@@ -878,7 +643,12 @@ class CLIBuilder {
878
643
  out.log(script);
879
644
  }
880
645
  });
881
- return this.command(cmd);
646
+
647
+ const withCompletions = this.command(cmd);
648
+ return new CLIBuilder({
649
+ ...withCompletions.schema,
650
+ hasBuiltInCompletions: true,
651
+ });
882
652
  }
883
653
 
884
654
  // -- Execution -----------------------------------------------------------
@@ -887,7 +657,7 @@ class CLIBuilder {
887
657
  * Execute the CLI program against explicit argv.
888
658
  *
889
659
  * This is the testable execution path — no process state is touched.
890
- * Returns a structured `RunResult` with exit code and captured output.
660
+ * Returns a structured {@linkcode RunResult} with exit code and captured output.
891
661
  *
892
662
  * @param argv - Raw argv tokens (NOT including the binary/script path,
893
663
  * i.e. equivalent to `process.argv.slice(2)`).
@@ -895,11 +665,9 @@ class CLIBuilder {
895
665
  * @returns Structured result with exit code and captured output.
896
666
  */
897
667
  async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
898
- // -- Detect --json flag (global, extracted before command dispatch) ------
668
+ // -- Detect global --json mode before building output ---------------------
899
669
  const hasJsonFlag = argv.includes('--json');
900
670
  const jsonMode = hasJsonFlag || options?.jsonMode === true;
901
- // Strip --json from argv so commands don't see it as an unknown flag
902
- const filteredArgv = hasJsonFlag ? argv.filter((a) => a !== '--json') : argv;
903
671
 
904
672
  const captureOptions = {
905
673
  ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
@@ -923,180 +691,74 @@ class CLIBuilder {
923
691
  binName: options?.help?.binName ?? this.schema.name,
924
692
  };
925
693
 
926
- // -- Root --version -------------------------------------------------------
927
- if (
928
- this.schema.version !== undefined &&
929
- (filteredArgv.includes('--version') || filteredArgv.includes('-V'))
930
- ) {
931
- out.log(this.schema.version);
932
- return buildResult(0, captured, undefined);
933
- }
934
-
935
- // -- Extract first arg for root-level checks --------------------------------
936
- const firstArg = filteredArgv.length > 0 ? filteredArgv[0] : undefined;
937
-
938
- // -- Root --help (explicit root-level help request) -----------------------
939
- // Only intercept when --help/-h is the first token — subcommand-level
940
- // help (e.g. `myapp deploy --help`) flows through dispatch.
941
- if (firstArg === '--help' || firstArg === '-h') {
942
- const helpText = formatRootHelp(this.schema, helpOptions);
943
- out.log(helpText);
944
- return buildResult(0, captured, undefined);
945
- }
946
-
947
- // -- `help [command...]` virtual subcommand ------------------------------
948
- // Rewrite `help <cmd>` → `<cmd> --help` so it flows through normal
949
- // dispatch and per-command help rendering. Bare `help` → root help.
950
- // Only activates when the user hasn't registered a real `help` command.
951
- if (firstArg === 'help') {
952
- const hasRealHelpCommand = this.schema.commands.some(
953
- (c) => c.schema.name === 'help' || c.schema.aliases.includes('help'),
954
- );
955
- if (!hasRealHelpCommand) {
956
- const rest = filteredArgv.slice(1);
957
- if (rest.length === 0) {
958
- const helpText = formatRootHelp(this.schema, helpOptions);
959
- out.log(helpText);
960
- return buildResult(0, captured, undefined);
961
- }
962
- // Recurse with rewritten argv: `help deploy --force` → `deploy --force --help`
963
- // Propagate jsonMode — `--json` was already stripped from filteredArgv above.
964
- return this.execute([...rest, '--help'], jsonMode ? { ...options, jsonMode } : options);
965
- }
966
- }
967
-
968
- // -- Empty argv without a default command → root help ---------------------
969
- if (firstArg === undefined && this.schema.defaultCommand === undefined) {
970
- const helpText = formatRootHelp(this.schema, helpOptions);
971
- out.log(helpText);
972
- return buildResult(0, captured, undefined);
973
- }
974
-
975
- // -- No commands registered -----------------------------------------------
976
- if (this.schema.commands.length === 0) {
977
- const err = new CLIError('No commands registered', {
978
- code: 'NO_ACTION',
979
- suggest: 'Add commands via .command() before calling .run()',
980
- });
981
- if (jsonMode) {
982
- out.json({ error: err.toJSON() });
983
- } else {
984
- out.error(err.message);
985
- }
986
- return buildResult(1, captured, err);
987
- }
988
-
989
- // -- Build root command map for dispatch -----------------------------------
990
- const rootCommands = buildRootCommandMap(this.schema.commands);
991
-
992
- // -- Recursive dispatch ---------------------------------------------------
993
- const result = dispatch(filteredArgv, rootCommands);
994
-
995
- // -- Resolve default command (if configured) ------------------------------
996
- const defaultCmd = this.schema.defaultCommand;
997
-
998
694
  // -- Shared options for command execution ----------------------------------
999
695
  const effectiveOptions: CLIRunOptions = {
1000
696
  ...options,
1001
697
  plugins: this.schema.plugins,
1002
698
  ...(jsonMode ? { jsonMode } : {}),
1003
699
  };
700
+ const output: OutputPolicy = {
701
+ jsonMode,
702
+ isTTY: out.isTTY,
703
+ verbosity: options?.verbosity ?? 'normal',
704
+ };
705
+ const planned = planInvocation({
706
+ schema: this.schema,
707
+ argv,
708
+ help: helpOptions,
709
+ output,
710
+ });
1004
711
 
1005
- switch (result.kind) {
1006
- case 'unknown': {
1007
- if (defaultCmd !== undefined && result.parentPath.length === 0) {
1008
- // Only delegate to the default command for root-level unknowns.
1009
- // Nested unknowns (parentPath non-empty) should surface an error
1010
- // so typo suggestions work correctly within command groups.
1011
- const suggestion =
1012
- result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
1013
- if (suggestion === undefined) {
1014
- const meta = buildMeta(this.schema, helpOptions, defaultCmd.schema.name);
1015
- const commandRunOptions = buildCommandRunOptions(effectiveOptions, helpOptions, meta);
1016
- return defaultCmd._execute(filteredArgv, { ...commandRunOptions });
1017
- }
1018
- }
712
+ switch (planned.kind) {
713
+ case 'root-version':
714
+ out.log(planned.version);
715
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
1019
716
 
1020
- if (result.input === '') {
1021
- // Only flags, no command, no default.
1022
- // Extract the first flag token to report it as unknown.
1023
- const unknownFlag = filteredArgv.find((t) => t.startsWith('-'));
1024
- if (unknownFlag !== undefined) {
1025
- const err = new ParseError(`Unknown flag ${unknownFlag}`, {
1026
- code: 'UNKNOWN_FLAG',
1027
- suggest: `Run '${this.schema.name} --help' for available commands`,
1028
- });
1029
- if (jsonMode) {
1030
- out.json({ error: err.toJSON() });
1031
- } else {
1032
- out.error(err.message);
1033
- out.error(`Suggestion: ${err.suggest}`);
1034
- }
1035
- return buildResult(2, captured, err);
1036
- }
1037
- // Truly empty (shouldn't reach here — handled above) — show help.
1038
- const helpText = formatRootHelp(this.schema, helpOptions);
1039
- out.log(helpText);
1040
- return buildResult(0, captured, undefined);
1041
- }
1042
- const suggestion = findClosestCommand(result.input, result.candidates);
1043
-
1044
- // Build scoped help path from ancestor context.
1045
- // e.g. for `myapp db migrat` → parentPath = [dbSchema] → "myapp db --help"
1046
- const scopePath =
1047
- result.parentPath.length > 0
1048
- ? `${this.schema.name} ${result.parentPath.map((s) => s.name).join(' ')}`
1049
- : this.schema.name;
1050
-
1051
- const err = new ParseError(`Unknown command: ${result.input}`, {
1052
- code: 'UNKNOWN_COMMAND',
1053
- suggest:
1054
- suggestion !== undefined
1055
- ? `Did you mean '${suggestion}'?`
1056
- : `Run '${scopePath} --help' for available commands`,
1057
- });
717
+ case 'root-help': {
718
+ const helpText = formatRootHelp(this.schema, planned.help);
719
+ out.log(helpText);
720
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
721
+ }
722
+
723
+ case 'dispatch-error': {
1058
724
  if (jsonMode) {
1059
- out.json({ error: err.toJSON() });
725
+ out.json({ error: planned.error.toJSON() });
1060
726
  } else {
1061
- out.error(err.message);
1062
- if (err.suggest !== undefined) {
1063
- out.error(`Suggestion: ${err.suggest}`);
727
+ out.error(planned.error.message);
728
+ if (planned.error.suggest !== undefined && planned.error.code !== 'NO_ACTION') {
729
+ out.error(`Suggestion: ${planned.error.suggest}`);
1064
730
  }
1065
731
  }
1066
- return buildResult(2, captured, err);
732
+ return buildRunResult({ exitCode: planned.error.exitCode, error: planned.error }, captured);
1067
733
  }
1068
734
 
1069
735
  case 'needs-subcommand': {
1070
- // Group command with no handler — show its help via formatHelp().
1071
- // Build binName from full command path so usage reads "myapp db" not just "db".
1072
- const ancestorNames = result.commandPath.slice(0, -1).map((s) => s.name);
1073
- const groupBinName = [this.schema.name, ...ancestorNames].join(' ');
1074
- const groupHelpOptions: HelpOptions = {
1075
- ...helpOptions,
1076
- binName: groupBinName,
1077
- };
1078
- const helpText = formatHelp(result.command.schema, groupHelpOptions);
736
+ const helpText = formatHelp(planned.command.schema, planned.help);
1079
737
  out.log(helpText);
1080
- return buildResult(0, captured, undefined);
738
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
1081
739
  }
1082
740
 
1083
741
  case 'match': {
1084
- // Merge propagated flags from ancestor path into target's schema.
1085
- const propagated = collectPropagatedFlags(result.commandPath);
1086
- const hasPropagated = Object.keys(propagated).length > 0;
1087
- const mergedSchema: CommandSchema | undefined = hasPropagated
1088
- ? {
1089
- ...result.command.schema,
1090
- flags: { ...propagated, ...result.command.schema.flags },
1091
- }
1092
- : undefined;
1093
-
1094
- const meta = buildMeta(this.schema, helpOptions, result.command.schema.name);
1095
- const commandRunOptions = buildCommandRunOptions(effectiveOptions, helpOptions, meta);
1096
- return result.command._execute(result.remainingArgv, {
1097
- ...commandRunOptions,
1098
- ...(mergedSchema !== undefined ? { mergedSchema } : {}),
742
+ const commandRunOptions = buildCommandRunOptions(
743
+ effectiveOptions,
744
+ planned.plan.help ?? helpOptions,
745
+ planned.plan.meta,
746
+ );
747
+ if (planned.plan.command._command === undefined) {
748
+ return planned.plan.command._execute(planned.plan.argv, {
749
+ ...commandRunOptions,
750
+ mergedSchema: planned.plan.mergedSchema,
751
+ });
752
+ }
753
+ const result = await executeCommand({
754
+ command: planned.plan.command._command,
755
+ argv: planned.plan.argv,
756
+ out,
757
+ schema: planned.plan.mergedSchema,
758
+ meta: planned.plan.meta,
759
+ options: commandRunOptions,
1099
760
  });
761
+ return buildRunResult(result, captured);
1100
762
  }
1101
763
  }
1102
764
  }
@@ -1111,7 +773,7 @@ class CLIBuilder {
1111
773
  * adapter). For testing, use `.execute()` instead — or provide a
1112
774
  * test adapter via `options.adapter`.
1113
775
  *
1114
- * Defaults to `createAdapter()` when no adapter is provided,
776
+ * Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
1115
777
  * which auto-detects the runtime (Node.js, Bun) and creates
1116
778
  * the appropriate adapter.
1117
779
  *
@@ -1121,123 +783,41 @@ class CLIBuilder {
1121
783
  const adapter = options?.adapter ?? createAdapter();
1122
784
  const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : undefined;
1123
785
 
1124
- const rawArgv = adapter.argv.slice(2);
1125
-
1126
- // Extract --config <path> / --config=<path> before command dispatch (requires I/O via adapter)
1127
- const { configPath, filteredArgv } = extractConfigFlag(rawArgv);
1128
-
1129
- // Detect --json early for error rendering during config loading
1130
- const hasJsonFlag = filteredArgv.includes('--json');
1131
- const jsonMode = hasJsonFlag || options?.jsonMode === true;
786
+ const preflight = await prepareRuntimePreflight({
787
+ schema: this.schema,
788
+ adapter,
789
+ options,
790
+ inheritedName,
791
+ });
1132
792
 
1133
- // Config discovery (only when .config() was called on the builder)
1134
- // Skip for completions subcommand — shell completions don't need config.
1135
- // Resolve the first argv token against registered commands (by name + aliases)
1136
- // so aliases or shadowed names are handled correctly.
1137
- // When no subcommand token is present and a default command exists, check
1138
- // whether the default command is 'completions' (unlikely but correct).
1139
- const firstToken = filteredArgv[0];
1140
- const matchedCommand =
1141
- firstToken !== undefined
1142
- ? this.schema.commands.find(
1143
- (c) => c.schema.name === firstToken || c.schema.aliases.includes(firstToken),
1144
- )
1145
- : undefined;
1146
- const effectiveCommandName =
1147
- matchedCommand?.schema.name ?? this.schema.defaultCommand?.schema.name;
1148
- const isCompletions = effectiveCommandName === 'completions';
1149
- let loadedConfig: Readonly<Record<string, unknown>> | undefined;
1150
-
1151
- if (
1152
- this.schema.configSettings !== undefined &&
1153
- !isCompletions &&
1154
- options?.config === undefined
1155
- ) {
1156
- try {
1157
- const result = await discoverConfig(this.schema.configSettings.appName, adapter, {
1158
- ...(configPath !== undefined ? { configPath } : {}),
1159
- ...(this.schema.configSettings.loaders !== undefined
1160
- ? { loaders: this.schema.configSettings.loaders }
1161
- : {}),
1162
- });
1163
- if (result.found) {
1164
- loadedConfig = result.data;
1165
- }
1166
- } catch (err: unknown) {
1167
- // Config errors are fatal — render and exit
1168
- if (err instanceof CLIError) {
1169
- if (jsonMode) {
1170
- adapter.stdout(`${JSON.stringify({ error: err.toJSON() })}\n`);
1171
- } else {
1172
- adapter.stderr(`Error: ${err.message}\n`);
1173
- if (err.suggest !== undefined) {
1174
- adapter.stderr(`Suggestion: ${err.suggest}\n`);
1175
- }
1176
- }
1177
- return adapter.exit(err.exitCode);
793
+ if (preflight.kind === 'config-error') {
794
+ if (preflight.jsonMode) {
795
+ adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
796
+ } else {
797
+ adapter.stderr(`Error: ${preflight.error.message}\n`);
798
+ if (preflight.error.suggest !== undefined) {
799
+ adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
1178
800
  }
1179
- throw err;
1180
801
  }
802
+ return adapter.exit(preflight.error.exitCode);
1181
803
  }
1182
804
 
1183
- // Package.json discovery (only when .packageJson() was called)
1184
- // Skip for completions subcommand — no metadata needed.
1185
- const packageJsonSettings = this.schema.packageJsonSettings;
1186
- const builderWithPackageJson =
1187
- packageJsonSettings !== undefined && !isCompletions
1188
- ? await (async (): Promise<CLIBuilder> => {
1189
- const pkg = await discoverPackageJson(adapter);
1190
- if (pkg === null) return this;
1191
-
1192
- const schema = this.schema;
1193
- const inferredName = packageJsonSettings.inferName ? inferCliName(pkg) : undefined;
1194
- return new CLIBuilder({
1195
- ...schema,
1196
- // Explicit > discovered: only fill in undefined fields
1197
- ...(schema.version === undefined && pkg.version !== undefined
1198
- ? { version: pkg.version }
1199
- : {}),
1200
- ...(schema.description === undefined && pkg.description !== undefined
1201
- ? { description: pkg.description }
1202
- : {}),
1203
- ...(inferredName !== undefined ? { name: inferredName } : {}),
1204
- });
1205
- })()
1206
- : this;
1207
805
  const effectiveBuilder =
1208
- inheritedName !== undefined
1209
- ? new CLIBuilder({ ...builderWithPackageJson.schema, name: inheritedName })
1210
- : builderWithPackageJson;
1211
-
1212
- // Auto-create terminal prompter when stdin is a TTY and no explicit prompter provided.
1213
- // This is the prompt gating seam: non-interactive environments (CI, piped stdin)
1214
- // get stdinIsTTY=false → no auto-prompter → prompts skipped → falls through to default/required.
1215
- const autoPrompter =
1216
- options?.prompter === undefined && adapter.stdinIsTTY
1217
- ? createTerminalPrompter(adapter.stdin, adapter.stderr)
1218
- : undefined;
1219
- const adapterStdinData =
1220
- options?.stdinData === undefined && invocationNeedsStdin(effectiveBuilder, filteredArgv)
1221
- ? await adapter.readStdin()
1222
- : undefined;
1223
-
1224
- // Source env, isTTY, and config from adapter when not explicitly provided in options
806
+ preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
1225
807
  const executeOptions: CLIRunOptions = {
1226
808
  ...options,
1227
- ...(options?.env === undefined ? { env: adapter.env } : {}),
1228
- ...(options?.isTTY === undefined ? { isTTY: adapter.isTTY } : {}),
1229
- ...(adapterStdinData !== undefined ? { stdinData: adapterStdinData } : {}),
1230
- ...(autoPrompter !== undefined ? { prompter: autoPrompter } : {}),
1231
- ...(loadedConfig !== undefined ? { config: loadedConfig } : {}),
809
+ ...preflight.inputs,
1232
810
  out: createOutput({
1233
811
  stdout: adapter.stdout,
1234
812
  stderr: adapter.stderr,
1235
- jsonMode,
1236
- isTTY: options?.isTTY ?? adapter.isTTY,
1237
- ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
813
+ jsonMode: preflight.inputs.jsonMode,
814
+ isTTY: preflight.inputs.isTTY,
815
+ ...(preflight.inputs.verbosity !== 'normal'
816
+ ? { verbosity: preflight.inputs.verbosity }
817
+ : {}),
1238
818
  }),
1239
819
  };
1240
- const result = await effectiveBuilder.execute(filteredArgv, executeOptions);
820
+ const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
1241
821
 
1242
822
  // Write captured output to real streams via adapter
1243
823
  for (const line of result.stdout) {
@@ -1250,33 +830,6 @@ class CLIBuilder {
1250
830
  return adapter.exit(result.exitCode);
1251
831
  }
1252
832
  }
1253
-
1254
- // --- Helpers
1255
-
1256
- /**
1257
- * Assemble a {@link RunResult} from its constituent parts.
1258
- *
1259
- * @param exitCode - Process exit code (0 = success).
1260
- * @param captured - Captured stdout/stderr/activity buffers.
1261
- * @param error - The originating error, if any.
1262
- * @returns Structured run result.
1263
- *
1264
- * @internal
1265
- */
1266
- function buildResult(
1267
- exitCode: number,
1268
- captured: CapturedOutput,
1269
- error: CLIError | undefined,
1270
- ): RunResult {
1271
- return {
1272
- exitCode,
1273
- stdout: captured.stdout,
1274
- stderr: captured.stderr,
1275
- activity: captured.activity,
1276
- error,
1277
- };
1278
- }
1279
-
1280
833
  const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
1281
834
 
1282
835
  /**
@@ -1376,8 +929,6 @@ interface CLIOptions {
1376
929
  *
1377
930
  * The CLI name is used in help text, usage lines, and generated completion scripts.
1378
931
  *
1379
- * @param nameOrOptions - Either the explicit CLI name or factory options.
1380
- *
1381
932
  * @example
1382
933
  * ```ts
1383
934
  * cli('mycli')
@@ -1394,6 +945,7 @@ interface CLIOptions {
1394
945
  */
1395
946
 
1396
947
  function cli(name: string): CLIBuilder;
948
+ /** Create a new CLI program builder from an options object. */
1397
949
  function cli(options: CLIOptions): CLIBuilder;
1398
950
  function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1399
951
  const name = typeof nameOrOptions === 'string' ? nameOrOptions : (nameOrOptions.name ?? 'cli');
@@ -1408,6 +960,7 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1408
960
  defaultCommand: undefined,
1409
961
  configSettings: undefined,
1410
962
  packageJsonSettings: undefined,
963
+ hasBuiltInCompletions: false,
1411
964
  plugins: [],
1412
965
  });
1413
966
  }