@kjanat/dreamcli 0.0.0 → 2.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 (205) hide show
  1. package/CHANGELOG.md +706 -0
  2. package/LICENSE +22 -0
  3. package/README.md +502 -0
  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 -0
  96. package/dist/index.mjs +1 -0
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/runtime/adapter.mjs +1 -0
  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 +7 -0
  115. package/dist/runtime.mjs +1 -0
  116. package/dist/testkit.d.mts +6 -0
  117. package/dist/testkit.mjs +1 -0
  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 +33 -0
  122. package/examples/gh/package.json +44 -0
  123. package/examples/gh/src/commands/auth.ts +66 -0
  124. package/examples/gh/src/commands/issue.ts +120 -0
  125. package/examples/gh/src/commands/pr.ts +125 -0
  126. package/examples/gh/src/data/issues.yaml +5 -0
  127. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  128. package/examples/gh/src/data/pull-requests.yaml +7 -0
  129. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  130. package/examples/gh/src/docs.ts +11 -0
  131. package/examples/gh/src/lib/auth.ts +37 -0
  132. package/examples/gh/src/lib/utils.ts +17 -0
  133. package/examples/gh/src/main.test.ts +307 -0
  134. package/examples/gh/src/main.ts +40 -0
  135. package/examples/interactive.ts +66 -0
  136. package/examples/json-mode.ts +91 -0
  137. package/examples/middleware.ts +71 -0
  138. package/examples/multi-command.ts +66 -0
  139. package/examples/spinner-progress.ts +49 -0
  140. package/examples/testing.ts +147 -0
  141. package/package.json +149 -2
  142. package/src/core/cli/dispatch.ts +286 -0
  143. package/src/core/cli/index.ts +978 -0
  144. package/src/core/cli/planner.ts +413 -0
  145. package/src/core/cli/plugin.ts +117 -0
  146. package/src/core/cli/propagate.ts +97 -0
  147. package/src/core/cli/root-help.ts +269 -0
  148. package/src/core/cli/root-surface.ts +74 -0
  149. package/src/core/cli/runtime-preflight.ts +409 -0
  150. package/src/core/completion/index.ts +88 -0
  151. package/src/core/completion/shells/bash.ts +459 -0
  152. package/src/core/completion/shells/fish.ts +259 -0
  153. package/src/core/completion/shells/powershell.ts +405 -0
  154. package/src/core/completion/shells/shared.ts +283 -0
  155. package/src/core/completion/shells/zsh.ts +381 -0
  156. package/src/core/config/index.ts +407 -0
  157. package/src/core/config/package-json.ts +220 -0
  158. package/src/core/errors/index.ts +193 -0
  159. package/src/core/execution/index.ts +270 -0
  160. package/src/core/help/index.ts +557 -0
  161. package/src/core/json-schema/index.ts +891 -0
  162. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  163. package/src/core/output/activity.ts +568 -0
  164. package/src/core/output/contracts.ts +194 -0
  165. package/src/core/output/display-value.ts +48 -0
  166. package/src/core/output/index.ts +669 -0
  167. package/src/core/output/renderers.ts +125 -0
  168. package/src/core/output/writer.ts +46 -0
  169. package/src/core/parse/index.ts +661 -0
  170. package/src/core/prompt/index.ts +583 -0
  171. package/src/core/resolve/args.ts +144 -0
  172. package/src/core/resolve/coerce.ts +432 -0
  173. package/src/core/resolve/config.ts +26 -0
  174. package/src/core/resolve/contracts.ts +135 -0
  175. package/src/core/resolve/errors.ts +227 -0
  176. package/src/core/resolve/flags.ts +205 -0
  177. package/src/core/resolve/index.ts +108 -0
  178. package/src/core/resolve/property.ts +99 -0
  179. package/src/core/schema/activity.ts +240 -0
  180. package/src/core/schema/arg.ts +719 -0
  181. package/src/core/schema/command.ts +1490 -0
  182. package/src/core/schema/flag.ts +756 -0
  183. package/src/core/schema/index.ts +91 -0
  184. package/src/core/schema/middleware.ts +171 -0
  185. package/src/core/schema/prompt.ts +156 -0
  186. package/src/core/schema/run.ts +195 -0
  187. package/src/core/schema-dsl/index.ts +109 -0
  188. package/src/core/schema-dsl/parse.ts +262 -0
  189. package/src/core/schema-dsl/runtime.ts +609 -0
  190. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  191. package/src/core/testkit/index.ts +123 -0
  192. package/src/index.ts +170 -0
  193. package/src/runtime/adapter.ts +303 -0
  194. package/src/runtime/auto.ts +110 -0
  195. package/src/runtime/bun.ts +55 -0
  196. package/src/runtime/deno.ts +369 -0
  197. package/src/runtime/detect.ts +105 -0
  198. package/src/runtime/index.ts +21 -0
  199. package/src/runtime/node-builtins.d.ts +23 -0
  200. package/src/runtime/node.ts +300 -0
  201. package/src/runtime/paths.ts +62 -0
  202. package/src/runtime/support.ts +135 -0
  203. package/src/runtime.ts +31 -0
  204. package/src/testkit.ts +25 -0
  205. package/src/version.ts +20 -0
@@ -0,0 +1,978 @@
1
+ /**
2
+ * CLI entry point builder with command registration and dispatch.
3
+ *
4
+ * The {@linkcode cli | cli()} factory returns an immutable {@linkcode CLIBuilder} that registers
5
+ * commands, handles `--help`/`--version` at root level, dispatches to
6
+ * the matched command, and provides both a testable `.execute()` path
7
+ * and a production `.run()` path.
8
+ *
9
+ * @module dreamcli/core/cli
10
+ */
11
+
12
+ import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
+ import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
14
+ import type { FormatLoader } from '#internals/core/config/index.ts';
15
+ import { CLIError } from '#internals/core/errors/index.ts';
16
+ import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
17
+ import type { HelpOptions } from '#internals/core/help/index.ts';
18
+ import { formatHelp } from '#internals/core/help/index.ts';
19
+ import type { CapturedOutput } from '#internals/core/output/index.ts';
20
+ import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
21
+ import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
22
+ import { arg } from '#internals/core/schema/arg.ts';
23
+ import type {
24
+ AnyCommandBuilder,
25
+ CommandBuilder,
26
+ CommandMeta,
27
+ CommandSchema,
28
+ ErasedCommand,
29
+ Out,
30
+ } from '#internals/core/schema/command.ts';
31
+ import { command } from '#internals/core/schema/command.ts';
32
+ import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
33
+ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
34
+ import { runCommand } from '#internals/core/testkit/index.ts';
35
+ import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
36
+ import { createAdapter } from '#internals/runtime/auto.ts';
37
+ import type { OutputPolicy } from './planner.ts';
38
+ import { planInvocation } from './planner.ts';
39
+ import type { CLIPlugin } from './plugin.ts';
40
+ import { plugin } from './plugin.ts';
41
+ import { formatRootHelp } from './root-help.ts';
42
+ import { prepareRuntimePreflight } from './runtime-preflight.ts';
43
+
44
+ // --- Type-erased command — erasure function (interface now in schema/command.ts)
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
+
98
+ /**
99
+ * Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
100
+ * building the subcommand tree.
101
+ *
102
+ * The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
103
+ * the original `CommandBuilder<F, A>` — no type assertions needed.\
104
+ * Subcommands are recursively erased and indexed by name and alias for
105
+ * O(1) lookup during dispatch.
106
+ *
107
+ * @internal
108
+ */
109
+ function eraseCommand<
110
+ F extends Record<string, FlagBuilder<FlagConfig>>,
111
+ A extends Record<string, ArgBuilder<ArgConfig>>,
112
+ C extends Record<string, unknown>,
113
+ >(cmd: CommandBuilder<F, A, C>): ErasedCommand {
114
+ // Recursively erase subcommands, keyed by name and alias.
115
+ const subcommands = new Map<string, ErasedCommand>();
116
+ const routeOwners = new Map<string, string>();
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
+
123
+ const erased = eraseCommand(sub);
124
+ for (const route of routes) {
125
+ subcommands.set(route, erased);
126
+ }
127
+ }
128
+
129
+ return {
130
+ schema: cmd.schema,
131
+ subcommands,
132
+ _command: cmd as unknown as AnyCommandBuilder,
133
+ _execute(argv, options) {
134
+ return runCommand(cmd, argv, options);
135
+ },
136
+ };
137
+ }
138
+
139
+ // --- CLI schema — runtime descriptor for the CLI program
140
+
141
+ /**
142
+ * Runtime descriptor for the CLI program.
143
+ *
144
+ * Stores the program name, version, description, and registered commands.\
145
+ * Built incrementally by {@linkcode CLIBuilder}.
146
+ */
147
+ interface CLISchema {
148
+ /** Program name (used in help text, usage lines, and completion scripts). */
149
+ readonly name: string;
150
+ /**
151
+ * Whether `.run()` should replace `name` with the invoked program name.
152
+ *
153
+ * Set via the `cli({ inherit: true })` factory form.
154
+ */
155
+ readonly inheritName: boolean;
156
+ /** Program version (shown by `--version`). */
157
+ readonly version: string | undefined;
158
+ /** Program description (shown in root help). */
159
+ readonly description: string | undefined;
160
+ /** Registered commands (type-erased for heterogeneous storage). */
161
+ readonly commands: readonly ErasedCommand[];
162
+ /**
163
+ * Default command dispatched when no subcommand matches.
164
+ *
165
+ * When set, the CLI root behaves like a hybrid command group: subcommands
166
+ * dispatch by name as usual, but empty argv or flags-only argv falls
167
+ * through to this command instead of showing root help.
168
+ *
169
+ * Set via the {@linkcode CLIBuilder.default | .default()} builder method.
170
+ */
171
+ readonly defaultCommand: ErasedCommand | undefined;
172
+ /**
173
+ * Config discovery settings.
174
+ *
175
+ * When defined, {@linkcode CLIBuilder.run | .run()} auto-discovers and loads a config file before command dispatch.
176
+ *
177
+ * Set via the {@linkcode CLIBuilder.config | .config()} builder method.
178
+ */
179
+ readonly configSettings: ConfigSettings | undefined;
180
+ /**
181
+ * Package.json auto-discovery settings. When defined, `.run()` discovers
182
+ * the nearest `package.json` and merges metadata before dispatch.
183
+ *
184
+ * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
185
+ */
186
+ readonly packageJsonSettings: PackageJsonSettings | undefined;
187
+ /** Whether built-in `.completions()` command registration is active. */
188
+ readonly hasBuiltInCompletions: boolean;
189
+ /** Registered CLI plugins. */
190
+ readonly plugins: readonly CLIPlugin[];
191
+ }
192
+
193
+ /**
194
+ * Config discovery settings for automatic config file loading.
195
+ *
196
+ * Stored in {@link CLISchema} and consumed by {@linkcode CLIBuilder.run()} to call
197
+ * {@link discoverConfig} before dispatching to a command.
198
+ */
199
+ interface ConfigSettings {
200
+ /**
201
+ * Application name used to build config search paths.
202
+ *
203
+ * Search paths: `.{appName}.json` (cwd), `{appName}.config.json` (cwd),
204
+ * and `{configDir}/{appName}/config.json` where `configDir` is
205
+ * `$XDG_CONFIG_HOME` / `~/.config` on Unix or `%APPDATA%` /
206
+ * `%USERPROFILE%\\AppData\\Roaming` on Windows.
207
+ */
208
+ readonly appName: string;
209
+
210
+ /** Additional format loaders beyond the built-in JSON loader. */
211
+ readonly loaders: readonly FormatLoader[] | undefined;
212
+ }
213
+
214
+ /**
215
+ * Package.json auto-discovery settings.
216
+ *
217
+ * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
218
+ * call {@link discoverPackageJson} before dispatching to a command.
219
+ */
220
+ interface PackageJsonSettings {
221
+ /**
222
+ * Infer CLI name from package.json `bin` keys or `name` field.
223
+ *
224
+ * When `true`, the discovered name replaces the `cli(name)` value.
225
+ * Explicit `.version()`/`.description()` calls still take precedence
226
+ * over discovered values.
227
+ *
228
+ * @defaultValue `false`
229
+ */
230
+ readonly inferName: boolean;
231
+ }
232
+
233
+ // --- Options for execute/run
234
+
235
+ /**
236
+ * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
237
+ *
238
+ * Derives from {@linkcode RunOptions} while excluding command-execution internals
239
+ * (`meta`, `mergedSchema`) and adding the CLI-level runtime adapter.
240
+ */
241
+ interface CLIRunOptions extends Omit<RunOptions, 'meta' | 'mergedSchema'> {
242
+ /**
243
+ * Runtime adapter providing platform-specific I/O, argv, env, etc.
244
+ *
245
+ * When provided to `.run()`, replaces the default Node adapter.
246
+ * Ignored by `.execute()` (which is process-free by design).
247
+ */
248
+ readonly adapter?: RuntimeAdapter;
249
+ }
250
+
251
+ // --- Command run options builder
252
+
253
+ /**
254
+ * Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
255
+ * field to satisfy `exactOptionalPropertyTypes`.
256
+ *
257
+ * @param options - CLI-level run options (may be `undefined` for defaults).
258
+ * @param helpOptions - Help formatting options forwarded to commands.
259
+ * @param meta - Optional command metadata (omitted for root-level dispatch).
260
+ * @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
261
+ *
262
+ * @internal
263
+ */
264
+ function buildCommandRunOptions(
265
+ options: CLIRunOptions | undefined,
266
+ helpOptions: HelpOptions,
267
+ meta?: CommandMeta,
268
+ ): RunOptions {
269
+ return {
270
+ help: helpOptions,
271
+ ...(meta !== undefined ? { meta } : {}),
272
+ ...(options?.plugins !== undefined ? { plugins: options.plugins } : {}),
273
+ ...(options?.env !== undefined ? { env: options.env } : {}),
274
+ ...(options?.config !== undefined ? { config: options.config } : {}),
275
+ ...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
276
+ ...(options?.prompter !== undefined ? { prompter: options.prompter } : {}),
277
+ ...(options?.answers !== undefined ? { answers: options.answers } : {}),
278
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
279
+ ...(options?.jsonMode !== undefined ? { jsonMode: options.jsonMode } : {}),
280
+ ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
281
+ ...(options?.out !== undefined ? { out: options.out } : {}),
282
+ ...(options?.captured !== undefined ? { captured: options.captured } : {}),
283
+ };
284
+ }
285
+
286
+ // --- CLIBuilder — immutable builder for the CLI program
287
+
288
+ /**
289
+ * Immutable CLI program builder.
290
+ *
291
+ * Registers commands, handles root-level `--help`/`--version`, and
292
+ * dispatches to the matched command based on argv.
293
+ *
294
+ * Two execution paths:
295
+ * - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
296
+ * - `.run(options?)` — production entry, reads `process.argv`, exits process
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * import { cli, command, flag, arg } from '@kjanat/dreamcli';
301
+ *
302
+ * const deploy = command('deploy')
303
+ * .arg('target', arg.string())
304
+ * .flag('force', flag.boolean().alias('f'))
305
+ * .action(({ args, flags, out }) => {
306
+ * out.log(`Deploying ${args.target}...`);
307
+ * });
308
+ *
309
+ * cli('mycli')
310
+ * .version('1.0.0')
311
+ * .command(deploy)
312
+ * .run();
313
+ * ```
314
+ */
315
+ class CLIBuilder {
316
+ /** @internal Runtime schema descriptor. */
317
+ readonly schema: CLISchema;
318
+
319
+ /** Build a CLIBuilder from a pre-constructed schema descriptor. */
320
+ constructor(schema: CLISchema) {
321
+ this.schema = schema;
322
+ }
323
+
324
+ // -- Metadata modifiers --------------------------------------------------
325
+
326
+ /**
327
+ * Set the program version (shown by `--version`).
328
+ *
329
+ * @param v - Semantic version string.
330
+ * @returns The builder (for chaining).
331
+ */
332
+ version(v: string): CLIBuilder {
333
+ return new CLIBuilder({ ...this.schema, version: v });
334
+ }
335
+
336
+ /**
337
+ * Set the program description (shown in root help).
338
+ *
339
+ * @param text - Short description displayed in root help output.
340
+ * @returns The builder (for chaining).
341
+ */
342
+ description(text: string): CLIBuilder {
343
+ return new CLIBuilder({ ...this.schema, description: text });
344
+ }
345
+
346
+ /**
347
+ * Enable automatic config file discovery.
348
+ *
349
+ * When enabled, `.run()` probes standard paths before dispatching:
350
+ * 1. `$CWD/.{appName}.json`
351
+ * 2. `$CWD/{appName}.config.json`
352
+ * 3. `$CONFIG_DIR/{appName}/config.json`
353
+ * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
354
+ * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
355
+ *
356
+ * The user can override the path via `--config <path>` or `--config=<path>`.
357
+ *
358
+ * Loaded config feeds into the resolution chain
359
+ * (CLI → env → **config** → prompt → default) for flags that
360
+ * declare `.config('dotted.path')`.
361
+ *
362
+ * Has no effect in `.execute()` (which receives config via
363
+ * `options.config` directly).
364
+ *
365
+ * @param appName - Name used to build search paths.
366
+ * @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
367
+ * @returns The builder (for chaining).
368
+ */
369
+ config(appName: string, loaders?: readonly FormatLoader[]): CLIBuilder {
370
+ return new CLIBuilder({
371
+ ...this.schema,
372
+ configSettings: {
373
+ appName,
374
+ loaders,
375
+ },
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Register a custom config format loader.
381
+ *
382
+ * Adds a {@link FormatLoader} incrementally — call multiple times to
383
+ * register multiple formats. Loaders registered later for the same
384
+ * extension override earlier ones.
385
+ *
386
+ * Requires `.config()` to have been called first (sets the app name).
387
+ *
388
+ * @param loader - Format loader (or extensions + parse function).
389
+ * @returns The builder (for chaining).
390
+ *
391
+ * @example Bun built-in parsers
392
+ * ```ts
393
+ * import { configFormat } from '@kjanat/dreamcli';
394
+ *
395
+ * cli('myapp')
396
+ * .config('myapp')
397
+ * .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
398
+ * .configLoader(configFormat(['toml'], Bun.TOML.parse))
399
+ * .run();
400
+ * ```
401
+ *
402
+ * @example npm package parsers
403
+ * ```ts
404
+ * import { configFormat } from '@kjanat/dreamcli';
405
+ * import { parse as parseYaml } from 'yaml';
406
+ * import { parse as parseTOML } from '@iarna/toml';
407
+ *
408
+ * cli('myapp')
409
+ * .config('myapp')
410
+ * .configLoader(configFormat(['yaml', 'yml'], parseYaml))
411
+ * .configLoader(configFormat(['toml'], parseTOML))
412
+ * .run();
413
+ * ```
414
+ */
415
+ configLoader(loader: FormatLoader): CLIBuilder {
416
+ if (this.schema.configSettings === undefined) {
417
+ throw new CLIError('.configLoader() requires .config() to be called first', {
418
+ code: 'INVALID_BUILDER_STATE',
419
+ suggest: 'Call .config(appName) before .configLoader()',
420
+ });
421
+ }
422
+ const existing = this.schema.configSettings.loaders ?? [];
423
+ return new CLIBuilder({
424
+ ...this.schema,
425
+ configSettings: {
426
+ ...this.schema.configSettings,
427
+ loaders: [...existing, loader],
428
+ },
429
+ });
430
+ }
431
+
432
+ /**
433
+ * Enable automatic package.json metadata discovery.
434
+ *
435
+ * When enabled, `.run()` walks up from `cwd` to find the nearest
436
+ * `package.json` and merges its `version` and `description` fields
437
+ * into the CLI schema. Explicit `.version()` and `.description()`
438
+ * calls always take precedence over discovered values.
439
+ *
440
+ * Has no effect in `.execute()` (which is filesystem-free by design).
441
+ *
442
+ * @param settings - Optional settings. Pass `{ inferName: true }` to
443
+ * also infer the CLI name from `bin` keys or the package `name` field.
444
+ *
445
+ * @example
446
+ * ```ts
447
+ * // Auto-fill version + description from nearest package.json:
448
+ * cli('mycli')
449
+ * .packageJson()
450
+ * .command(deploy)
451
+ * .run();
452
+ *
453
+ * // Also infer CLI name from bin key / package name:
454
+ * cli('mycli')
455
+ * .packageJson({ inferName: true })
456
+ * .command(deploy)
457
+ * .run();
458
+ *
459
+ * // Explicit values always win:
460
+ * cli('mycli')
461
+ * .packageJson()
462
+ * .version('2.0.0-beta') // wins over package.json
463
+ * .run();
464
+ * ```
465
+ */
466
+ packageJson(settings?: { readonly inferName?: boolean }): CLIBuilder {
467
+ return new CLIBuilder({
468
+ ...this.schema,
469
+ packageJsonSettings: {
470
+ inferName: settings?.inferName ?? false,
471
+ },
472
+ });
473
+ }
474
+
475
+ // -- Command registration ------------------------------------------------
476
+
477
+ /**
478
+ * Register a command with the CLI program.
479
+ *
480
+ * The command's type parameters are erased for heterogeneous storage.
481
+ * Type safety is preserved inside the closure that delegates to
482
+ * {@linkcode runCommand | runCommand()}.
483
+ *
484
+ * @param cmd - {@link CommandBuilder} to register.
485
+ * @returns The builder (for chaining).
486
+ */
487
+ command<
488
+ F extends Record<string, FlagBuilder<FlagConfig>>,
489
+ A extends Record<string, ArgBuilder<ArgConfig>>,
490
+ C extends Record<string, unknown>,
491
+ >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
492
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
493
+
494
+ return new CLIBuilder({
495
+ ...this.schema,
496
+ commands: [...this.schema.commands, eraseCommand(cmd)],
497
+ });
498
+ }
499
+
500
+ /**
501
+ * Register a command as the default — dispatched when no subcommand is given.
502
+ *
503
+ * The CLI root behaves like a hybrid command group: named subcommands
504
+ * dispatch normally, but empty argv or flags-only argv falls through to
505
+ * this command instead of showing root help.
506
+ *
507
+ * The command is also registered as a normal subcommand (can be invoked
508
+ * by name). Only one default command is allowed.
509
+ *
510
+ * @example
511
+ * ```ts
512
+ * // Single-command CLI — no subcommand name needed:
513
+ * // mytool --force production
514
+ * cli('mytool')
515
+ * .default(deploy)
516
+ * .run();
517
+ *
518
+ * // Multi-command CLI with a default:
519
+ * // mytool production → runs deploy
520
+ * // mytool status → runs status
521
+ * cli('mytool')
522
+ * .default(deploy)
523
+ * .command(status)
524
+ * .run();
525
+ * ```
526
+ *
527
+ * @param cmd - {@link CommandBuilder} to register as the default.
528
+ * @returns The builder (for chaining).
529
+ */
530
+ default<
531
+ F extends Record<string, FlagBuilder<FlagConfig>>,
532
+ A extends Record<string, ArgBuilder<ArgConfig>>,
533
+ C extends Record<string, unknown>,
534
+ >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
535
+ if (this.schema.defaultCommand !== undefined) {
536
+ throw new CLIError('Only one default command is allowed', {
537
+ code: 'DUPLICATE_DEFAULT',
538
+ suggest: 'Call .default() only once when building the CLI',
539
+ });
540
+ }
541
+
542
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
543
+
544
+ const erased = eraseCommand(cmd);
545
+ return new CLIBuilder({
546
+ ...this.schema,
547
+ commands: [...this.schema.commands, erased],
548
+ defaultCommand: erased,
549
+ });
550
+ }
551
+
552
+ /**
553
+ * Register a CLI plugin.
554
+ *
555
+ * Plugins run in registration order. At each lifecycle stage, all hooks for
556
+ * the first plugin run before hooks for the second plugin, and so on.
557
+ *
558
+ * @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
559
+ * @returns The builder (for chaining).
560
+ * @see {@link plugin} to construct plugin definitions.
561
+ */
562
+ plugin(definition: CLIPlugin): CLIBuilder {
563
+ return new CLIBuilder({
564
+ ...this.schema,
565
+ plugins: [...this.schema.plugins, definition],
566
+ });
567
+ }
568
+
569
+ // -- Built-in subcommands ------------------------------------------------
570
+
571
+ /**
572
+ * Register a built-in `completions` subcommand that generates shell
573
+ * completion scripts.
574
+ *
575
+ * The generated command accepts a `--shell` flag (required, enum of
576
+ * all {@link Shell} values) and writes the completion script to stdout
577
+ * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
578
+ * instead of a generic parse error.
579
+ *
580
+ * Call this **after** registering all other commands so the completion
581
+ * script includes the full command set. The captured schema is a
582
+ * snapshot at call time — commands registered after `.completions()`
583
+ * will not appear in the generated script. Completion options are also
584
+ * captured at call time.
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * cli('mycli')
589
+ * .version('1.0.0')
590
+ * .command(deploy)
591
+ * .command(login)
592
+ * .completions({ rootMode: 'surface' })
593
+ * .run();
594
+ * ```
595
+ */
596
+ completions(options?: CompletionOptions): CLIBuilder {
597
+ if (this.schema.hasBuiltInCompletions) {
598
+ throw new CLIError('.completions() has already been called', {
599
+ code: 'DUPLICATE_COMMAND',
600
+ suggest: 'Call .completions() only once when building the CLI',
601
+ });
602
+ }
603
+
604
+ // Capture current schema — includes all commands registered so far.
605
+ // The completions command itself is deliberately excluded from the
606
+ // generated script (it would be noise in shell completions).
607
+ const cliSchema = this.schema;
608
+ const completionOptions = options;
609
+
610
+ // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
611
+ const shellMap = new Map<string, Shell>();
612
+ for (const s of SHELLS) shellMap.set(s, s);
613
+ shellMap.set('pwsh', 'powershell');
614
+
615
+ const cmd = command('completions')
616
+ .alias('completion')
617
+ .description('Generate shell completion script')
618
+ .arg(
619
+ 'shell',
620
+ arg
621
+ .custom((raw: string): Shell => {
622
+ // Normalize $SHELL paths across Unix/Windows:
623
+ // /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
624
+ const segments = raw.split(/[\\/]/);
625
+ const basename = segments[segments.length - 1] ?? raw;
626
+ const name = basename.replace(/\.(?:exe|cmd|bat)$/i, '');
627
+ const shell = shellMap.get(name);
628
+ if (shell === undefined) {
629
+ throw new Error(`Unknown shell '${name}'. Valid shells: ${SHELLS.join(', ')}`);
630
+ }
631
+ return shell;
632
+ })
633
+ .env('SHELL')
634
+ .describe(`Target shell (${SHELLS.join(', ')})`),
635
+ )
636
+ .action(({ args, meta, out }) => {
637
+ const completionSchema =
638
+ meta.bin === cliSchema.name ? cliSchema : { ...cliSchema, name: meta.bin };
639
+ const script = generateCompletion(completionSchema, args.shell, completionOptions);
640
+ if (out.jsonMode) {
641
+ out.json({ shell: args.shell, script });
642
+ } else {
643
+ out.log(script);
644
+ }
645
+ });
646
+
647
+ const withCompletions = this.command(cmd);
648
+ return new CLIBuilder({
649
+ ...withCompletions.schema,
650
+ hasBuiltInCompletions: true,
651
+ });
652
+ }
653
+
654
+ // -- Execution -----------------------------------------------------------
655
+
656
+ /**
657
+ * Execute the CLI program against explicit argv.
658
+ *
659
+ * This is the testable execution path — no process state is touched.
660
+ * Returns a structured {@linkcode RunResult} with exit code and captured output.
661
+ *
662
+ * @param argv - Raw argv tokens (NOT including the binary/script path,
663
+ * i.e. equivalent to `process.argv.slice(2)`).
664
+ * @param options - Injectable runtime state.
665
+ * @returns Structured result with exit code and captured output.
666
+ */
667
+ async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
668
+ // -- Detect global --json mode before building output ---------------------
669
+ const hasJsonFlag = argv.includes('--json');
670
+ const jsonMode = hasJsonFlag || options?.jsonMode === true;
671
+
672
+ const captureOptions = {
673
+ ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
674
+ ...(jsonMode ? { jsonMode } : {}),
675
+ ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
676
+ };
677
+ let out: Out;
678
+ let captured: CapturedOutput;
679
+ if (options?.out !== undefined) {
680
+ out = options.out;
681
+ captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
682
+ } else {
683
+ [out, captured] = createCaptureOutput(
684
+ Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
685
+ );
686
+ }
687
+
688
+ // Resolve help options — default binName to CLI program name
689
+ const helpOptions: HelpOptions = {
690
+ ...options?.help,
691
+ binName: options?.help?.binName ?? this.schema.name,
692
+ };
693
+
694
+ // -- Shared options for command execution ----------------------------------
695
+ const effectiveOptions: CLIRunOptions = {
696
+ ...options,
697
+ plugins: this.schema.plugins,
698
+ ...(jsonMode ? { jsonMode } : {}),
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
+ });
711
+
712
+ switch (planned.kind) {
713
+ case 'root-version':
714
+ out.log(planned.version);
715
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
716
+
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': {
724
+ if (jsonMode) {
725
+ out.json({ error: planned.error.toJSON() });
726
+ } else {
727
+ out.error(planned.error.message);
728
+ if (planned.error.suggest !== undefined && planned.error.code !== 'NO_ACTION') {
729
+ out.error(`Suggestion: ${planned.error.suggest}`);
730
+ }
731
+ }
732
+ return buildRunResult({ exitCode: planned.error.exitCode, error: planned.error }, captured);
733
+ }
734
+
735
+ case 'needs-subcommand': {
736
+ const helpText = formatHelp(planned.command.schema, planned.help);
737
+ out.log(helpText);
738
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
739
+ }
740
+
741
+ case 'match': {
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,
760
+ });
761
+ return buildRunResult(result, captured);
762
+ }
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Run the CLI program as a production entry point.
768
+ *
769
+ * Reads argv from the runtime adapter, dispatches to the matched
770
+ * command, writes output to real streams, and exits the process.
771
+ *
772
+ * This is the **only** place that touches process state (via the
773
+ * adapter). For testing, use `.execute()` instead — or provide a
774
+ * test adapter via `options.adapter`.
775
+ *
776
+ * Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
777
+ * which auto-detects the runtime (Node.js, Bun) and creates
778
+ * the appropriate adapter.
779
+ *
780
+ * @param options - Optional runtime configuration including adapter.
781
+ */
782
+ async run(options?: CLIRunOptions): Promise<never> {
783
+ const adapter = options?.adapter ?? createAdapter();
784
+ const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : undefined;
785
+
786
+ const preflight = await prepareRuntimePreflight({
787
+ schema: this.schema,
788
+ adapter,
789
+ options,
790
+ inheritedName,
791
+ });
792
+
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`);
800
+ }
801
+ }
802
+ return adapter.exit(preflight.error.exitCode);
803
+ }
804
+
805
+ const effectiveBuilder =
806
+ preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
807
+ const executeOptions: CLIRunOptions = {
808
+ ...options,
809
+ ...preflight.inputs,
810
+ out: createOutput({
811
+ stdout: adapter.stdout,
812
+ stderr: adapter.stderr,
813
+ jsonMode: preflight.inputs.jsonMode,
814
+ isTTY: preflight.inputs.isTTY,
815
+ ...(preflight.inputs.verbosity !== 'normal'
816
+ ? { verbosity: preflight.inputs.verbosity }
817
+ : {}),
818
+ }),
819
+ };
820
+ const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
821
+
822
+ // Write captured output to real streams via adapter
823
+ for (const line of result.stdout) {
824
+ adapter.stdout(line);
825
+ }
826
+ for (const line of result.stderr) {
827
+ adapter.stderr(line);
828
+ }
829
+
830
+ return adapter.exit(result.exitCode);
831
+ }
832
+ }
833
+ const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
834
+
835
+ /**
836
+ * Extract the final path segment from a path-like or URL-like string.
837
+ *
838
+ * @param input - Forward- or backslash-delimited path.
839
+ * @returns Trailing segment, or `undefined` when the input is empty or slash-only.
840
+ *
841
+ * @internal
842
+ */
843
+ function basename(input: string): string | undefined {
844
+ const trimmed = input.replace(/[\\/]+$/g, '');
845
+ if (trimmed.length === 0) return undefined;
846
+ const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
847
+ const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
848
+ return name.length > 0 ? name : undefined;
849
+ }
850
+
851
+ /**
852
+ * Detect known interpreter/runtime binary names (node, bun, deno, tsx).
853
+ *
854
+ * @param input - Candidate binary name, with or without `.exe` suffix.
855
+ * @returns `true` when `input` matches a known runtime after normalization.
856
+ *
857
+ * @internal
858
+ */
859
+ function isRuntimeBinaryName(input: string): boolean {
860
+ const normalized = input.toLowerCase().replace(/\.exe$/i, '');
861
+ return RUNTIME_BINARIES.has(normalized);
862
+ }
863
+
864
+ /**
865
+ * Infer the displayed CLI name from the current runtime invocation.
866
+ *
867
+ * Resolution order:
868
+ * 1. Node/Bun/tsx-style interpreters → script/entry argument basename
869
+ * 2. Standalone executable invocations → argv[0] basename
870
+ * 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
871
+ *
872
+ * @param argv - Full process argv (typically `process.argv` or adapter equivalent).
873
+ * @returns Inferred program name, or `undefined` when inference is ambiguous.
874
+ *
875
+ * @internal
876
+ */
877
+ function inferInvocationName(argv: readonly string[]): string | undefined {
878
+ const argv0 = argv[0];
879
+ const argv1 = argv[1];
880
+ const runtimeName = argv0 !== undefined ? basename(argv0) : undefined;
881
+
882
+ if (runtimeName !== undefined && isRuntimeBinaryName(runtimeName)) {
883
+ if (runtimeName === 'bun' && argv1 === 'run') {
884
+ const entryArg = argv[2];
885
+ if (entryArg === undefined || entryArg.startsWith('-')) return undefined;
886
+ return basename(entryArg);
887
+ }
888
+ if (runtimeName === 'deno' && argv1 === 'run') return undefined;
889
+ if (argv1 === undefined || argv1.startsWith('-')) return undefined;
890
+ return basename(argv1);
891
+ }
892
+
893
+ return argv0 !== undefined ? basename(argv0) : undefined;
894
+ }
895
+
896
+ // --- Factory function
897
+
898
+ /**
899
+ * Options for the `cli({...})` factory form.
900
+ *
901
+ * This form is useful when the displayed CLI name should be inferred from the
902
+ * current runtime invocation instead of always being hard-coded.
903
+ */
904
+ interface CLIOptions {
905
+ /**
906
+ * Explicit fallback CLI name.
907
+ *
908
+ * Used by `.execute()`, and by `.run()` when runtime name inheritance is
909
+ * disabled or the invocation name cannot be inferred.
910
+ *
911
+ * @defaultValue `'cli'`
912
+ */
913
+ readonly name?: string;
914
+
915
+ /**
916
+ * Replace `name` with the invoked program basename during `.run()`.
917
+ *
918
+ * Examples:
919
+ * - `node ./bin/mycli.ts` → `mycli.ts`
920
+ * - `/usr/local/bin/mycli` → `mycli`
921
+ *
922
+ * @defaultValue `false`
923
+ */
924
+ readonly inherit?: boolean;
925
+ }
926
+
927
+ /**
928
+ * Create a new CLI program builder.
929
+ *
930
+ * The CLI name is used in help text, usage lines, and generated completion scripts.
931
+ *
932
+ * @example
933
+ * ```ts
934
+ * cli('mycli')
935
+ * .version('1.0.0')
936
+ * .description('My awesome tool')
937
+ * .command(deploy)
938
+ * .command(login)
939
+ * .run();
940
+ *
941
+ * cli({ inherit: true })
942
+ * .command(deploy)
943
+ * .run();
944
+ * ```
945
+ */
946
+
947
+ function cli(name: string): CLIBuilder;
948
+ /** Create a new CLI program builder from an options object. */
949
+ function cli(options: CLIOptions): CLIBuilder;
950
+ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
951
+ const name = typeof nameOrOptions === 'string' ? nameOrOptions : (nameOrOptions.name ?? 'cli');
952
+ const inheritName = typeof nameOrOptions === 'string' ? false : (nameOrOptions.inherit ?? false);
953
+
954
+ return new CLIBuilder({
955
+ name,
956
+ inheritName,
957
+ version: undefined,
958
+ description: undefined,
959
+ commands: [],
960
+ defaultCommand: undefined,
961
+ configSettings: undefined,
962
+ packageJsonSettings: undefined,
963
+ hasBuiltInCompletions: false,
964
+ plugins: [],
965
+ });
966
+ }
967
+
968
+ // --- Exports
969
+
970
+ export type {
971
+ BeforeParseParams,
972
+ CLIPlugin,
973
+ CLIPluginHooks,
974
+ PluginCommandContext,
975
+ ResolvedCommandParams,
976
+ } from './plugin.ts';
977
+ export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
978
+ export { CLIBuilder, cli, formatRootHelp, plugin };