@kjanat/dreamcli 2.5.0 → 3.0.0-rc.10

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 (202) hide show
  1. package/CHANGELOG.md +344 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.d.mts +6 -5
  4. package/dist/core/cli/dispatch.mjs +205 -1
  5. package/dist/core/cli/help-links.d.mts +0 -1
  6. package/dist/core/cli/help-links.mjs +41 -1
  7. package/dist/core/cli/index.d.mts +185 -19
  8. package/dist/core/cli/index.mjs +945 -1
  9. package/dist/core/cli/planner.d.mts +32 -6
  10. package/dist/core/cli/planner.mjs +300 -1
  11. package/dist/core/cli/plugin.d.mts +1 -1
  12. package/dist/core/cli/plugin.mjs +41 -1
  13. package/dist/core/cli/propagate.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +57 -1
  15. package/dist/core/cli/root-help.d.mts +18 -3
  16. package/dist/core/cli/root-help.mjs +226 -6
  17. package/dist/core/cli/root-surface.d.mts +30 -4
  18. package/dist/core/cli/root-surface.mjs +28 -1
  19. package/dist/core/cli/runtime-preflight.d.mts +30 -3
  20. package/dist/core/cli/runtime-preflight.mjs +169 -1
  21. package/dist/core/completion/index.d.mts +32 -2
  22. package/dist/core/completion/index.mjs +90 -1
  23. package/dist/core/completion/shells/bash.d.mts +0 -1
  24. package/dist/core/completion/shells/bash.mjs +308 -3
  25. package/dist/core/completion/shells/fish.d.mts +0 -1
  26. package/dist/core/completion/shells/fish.mjs +162 -2
  27. package/dist/core/completion/shells/powershell.d.mts +0 -1
  28. package/dist/core/completion/shells/powershell.mjs +358 -2
  29. package/dist/core/completion/shells/shared.d.mts +23 -2
  30. package/dist/core/completion/shells/shared.mjs +176 -1
  31. package/dist/core/completion/shells/zsh.d.mts +0 -1
  32. package/dist/core/completion/shells/zsh.mjs +251 -2
  33. package/dist/core/config/index.d.mts +2 -3
  34. package/dist/core/config/index.mjs +246 -1
  35. package/dist/core/config/package-json.d.mts +27 -4
  36. package/dist/core/config/package-json.mjs +386 -3
  37. package/dist/core/errors/index.d.mts +3 -3
  38. package/dist/core/errors/index.mjs +87 -1
  39. package/dist/core/execution/index.d.mts +0 -1
  40. package/dist/core/execution/index.mjs +201 -1
  41. package/dist/core/help/ansi.d.mts +11 -5
  42. package/dist/core/help/ansi.mjs +121 -2
  43. package/dist/core/help/index.d.mts +65 -2
  44. package/dist/core/help/index.mjs +341 -7
  45. package/dist/core/help/theme.d.mts +68 -0
  46. package/dist/core/help/theme.mjs +46 -0
  47. package/dist/core/json-schema/index.d.mts +15 -2
  48. package/dist/core/json-schema/index.mjs +536 -12
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  51. package/dist/core/output/activity.d.mts +0 -1
  52. package/dist/core/output/activity.mjs +452 -1
  53. package/dist/core/output/bind.mjs +56 -1
  54. package/dist/core/output/contracts.d.mts +4 -5
  55. package/dist/core/output/contracts.mjs +57 -1
  56. package/dist/core/output/display-value.mjs +32 -1
  57. package/dist/core/output/index.d.mts +21 -1
  58. package/dist/core/output/index.mjs +442 -2
  59. package/dist/core/output/renderers.d.mts +0 -1
  60. package/dist/core/output/renderers.mjs +46 -1
  61. package/dist/core/output/writer.mjs +12 -1
  62. package/dist/core/parse/index.d.mts +54 -7
  63. package/dist/core/parse/index.mjs +727 -1
  64. package/dist/core/prompt/index.d.mts +12 -4
  65. package/dist/core/prompt/index.mjs +348 -6
  66. package/dist/core/resolve/args.d.mts +1 -1
  67. package/dist/core/resolve/args.mjs +105 -1
  68. package/dist/core/resolve/coerce.d.mts +1 -1
  69. package/dist/core/resolve/coerce.mjs +336 -1
  70. package/dist/core/resolve/config.mjs +19 -1
  71. package/dist/core/resolve/contracts.d.mts +9 -4
  72. package/dist/core/resolve/errors.d.mts +0 -1
  73. package/dist/core/resolve/errors.mjs +140 -2
  74. package/dist/core/resolve/flags.d.mts +7 -2
  75. package/dist/core/resolve/flags.mjs +251 -1
  76. package/dist/core/resolve/index.d.mts +2 -2
  77. package/dist/core/resolve/index.mjs +85 -1
  78. package/dist/core/resolve/property.d.mts +6 -2
  79. package/dist/core/resolve/property.mjs +53 -1
  80. package/dist/core/schema/activity.d.mts +31 -11
  81. package/dist/core/schema/arg.d.mts +92 -13
  82. package/dist/core/schema/arg.mjs +463 -1
  83. package/dist/core/schema/command.d.mts +29 -7
  84. package/dist/core/schema/command.mjs +726 -1
  85. package/dist/core/schema/flag.d.mts +577 -21
  86. package/dist/core/schema/flag.mjs +705 -1
  87. package/dist/core/schema/index.d.mts +5 -2
  88. package/dist/core/schema/middleware.d.mts +4 -3
  89. package/dist/core/schema/middleware.mjs +41 -1
  90. package/dist/core/schema/number-constraints.d.mts +96 -0
  91. package/dist/core/schema/number-constraints.mjs +60 -0
  92. package/dist/core/schema/prompt.d.mts +21 -3
  93. package/dist/core/schema/run.d.mts +24 -5
  94. package/dist/core/schema/string-constraints.d.mts +97 -0
  95. package/dist/core/schema/string-constraints.mjs +69 -0
  96. package/dist/core/schema/value-parsers.d.mts +78 -0
  97. package/dist/core/schema/value-parsers.mjs +142 -0
  98. package/dist/core/schema-dsl/runtime.mjs +271 -2
  99. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  100. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  101. package/dist/core/testkit/index.d.mts +9 -36
  102. package/dist/core/testkit/index.mjs +83 -1
  103. package/dist/index.d.mts +12 -6
  104. package/dist/index.mjs +22 -1
  105. package/dist/runtime/adapter.d.mts +38 -2
  106. package/dist/runtime/adapter.mjs +87 -1
  107. package/dist/runtime/auto.d.mts +2 -3
  108. package/dist/runtime/auto.mjs +45 -1
  109. package/dist/runtime/deno.d.mts +24 -5
  110. package/dist/runtime/deno.mjs +262 -2
  111. package/dist/runtime/detect.mjs +45 -1
  112. package/dist/runtime/index.d.mts +3 -4
  113. package/dist/runtime/node.d.mts +8 -2
  114. package/dist/runtime/node.mjs +220 -2
  115. package/dist/runtime/paths.mjs +48 -1
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +6 -1
  118. package/dist/strings.mjs +22 -1
  119. package/dist/testkit.d.mts +1 -0
  120. package/dist/testkit.mjs +5 -1
  121. package/dist/version.d.mts +7 -3
  122. package/dist/version.mjs +7 -1
  123. package/dreamcli.schema.json +36 -7
  124. package/examples/basic.ts +5 -1
  125. package/examples/gh/package.json +2 -7
  126. package/examples/pwsh-demo/package.json +1 -7
  127. package/examples/pwsh-demo/src/main.test.ts +1 -4
  128. package/examples/pwsh-demo/src/main.ts +14 -4
  129. package/examples/transport-launcher.ts +85 -0
  130. package/package.json +43 -49
  131. package/dist/runtime/bun.d.mts +0 -28
  132. package/dist/runtime/bun.mjs +0 -1
  133. package/dist/runtime/support.d.mts +0 -42
  134. package/dist/runtime/support.mjs +0 -1
  135. package/src/core/cli/dispatch.ts +0 -349
  136. package/src/core/cli/help-links.ts +0 -82
  137. package/src/core/cli/index.ts +0 -1413
  138. package/src/core/cli/planner.ts +0 -487
  139. package/src/core/cli/plugin.ts +0 -117
  140. package/src/core/cli/propagate.ts +0 -97
  141. package/src/core/cli/root-help.ts +0 -252
  142. package/src/core/cli/root-surface.ts +0 -74
  143. package/src/core/cli/runtime-preflight.ts +0 -438
  144. package/src/core/completion/index.ts +0 -88
  145. package/src/core/completion/shells/bash.ts +0 -459
  146. package/src/core/completion/shells/fish.ts +0 -259
  147. package/src/core/completion/shells/powershell.ts +0 -439
  148. package/src/core/completion/shells/shared.ts +0 -283
  149. package/src/core/completion/shells/zsh.ts +0 -381
  150. package/src/core/config/index.ts +0 -417
  151. package/src/core/config/package-json.ts +0 -560
  152. package/src/core/errors/index.ts +0 -193
  153. package/src/core/execution/index.ts +0 -268
  154. package/src/core/help/ansi.ts +0 -144
  155. package/src/core/help/index.ts +0 -516
  156. package/src/core/json-schema/index.ts +0 -891
  157. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  158. package/src/core/output/activity.ts +0 -575
  159. package/src/core/output/bind.ts +0 -59
  160. package/src/core/output/contracts.ts +0 -194
  161. package/src/core/output/display-value.ts +0 -48
  162. package/src/core/output/index.ts +0 -704
  163. package/src/core/output/renderers.ts +0 -125
  164. package/src/core/output/writer.ts +0 -46
  165. package/src/core/parse/index.ts +0 -681
  166. package/src/core/prompt/index.ts +0 -583
  167. package/src/core/resolve/args.ts +0 -144
  168. package/src/core/resolve/coerce.ts +0 -432
  169. package/src/core/resolve/config.ts +0 -26
  170. package/src/core/resolve/contracts.ts +0 -135
  171. package/src/core/resolve/errors.ts +0 -227
  172. package/src/core/resolve/flags.ts +0 -255
  173. package/src/core/resolve/index.ts +0 -108
  174. package/src/core/resolve/property.ts +0 -99
  175. package/src/core/schema/activity.ts +0 -240
  176. package/src/core/schema/arg.ts +0 -719
  177. package/src/core/schema/command.ts +0 -1498
  178. package/src/core/schema/flag.ts +0 -801
  179. package/src/core/schema/index.ts +0 -91
  180. package/src/core/schema/middleware.ts +0 -171
  181. package/src/core/schema/prompt.ts +0 -156
  182. package/src/core/schema/run.ts +0 -198
  183. package/src/core/schema-dsl/index.ts +0 -109
  184. package/src/core/schema-dsl/parse.ts +0 -262
  185. package/src/core/schema-dsl/runtime.ts +0 -609
  186. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  187. package/src/core/testkit/index.ts +0 -123
  188. package/src/index.ts +0 -179
  189. package/src/runtime/adapter.ts +0 -303
  190. package/src/runtime/auto.ts +0 -110
  191. package/src/runtime/bun.ts +0 -55
  192. package/src/runtime/deno.ts +0 -369
  193. package/src/runtime/detect.ts +0 -105
  194. package/src/runtime/index.ts +0 -21
  195. package/src/runtime/node-builtins.d.ts +0 -27
  196. package/src/runtime/node.ts +0 -300
  197. package/src/runtime/paths.ts +0 -64
  198. package/src/runtime/support.ts +0 -135
  199. package/src/runtime.ts +0 -31
  200. package/src/strings.ts +0 -34
  201. package/src/testkit.ts +0 -25
  202. package/src/version.ts +0 -20
@@ -1,1413 +0,0 @@
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 type { PackageJsonData } from '#internals/core/config/package-json.ts';
16
- import { CLIError } from '#internals/core/errors/index.ts';
17
- import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
18
- import type { HelpOptions } from '#internals/core/help/index.ts';
19
- import { formatHelp } from '#internals/core/help/index.ts';
20
- import type { CapturedOutput } from '#internals/core/output/index.ts';
21
- import {
22
- clearRequestedExitCode,
23
- createCaptureOutput,
24
- createOutput,
25
- } from '#internals/core/output/index.ts';
26
- import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
27
- import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
28
- import { arg } from '#internals/core/schema/arg.ts';
29
- import type {
30
- AnyCommandBuilder,
31
- CommandBuilder,
32
- CommandMeta,
33
- CommandSchema,
34
- ErasedCommand,
35
- Out,
36
- } from '#internals/core/schema/command.ts';
37
- import { command } from '#internals/core/schema/command.ts';
38
- import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
39
- import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
40
- import { runCommand } from '#internals/core/testkit/index.ts';
41
- import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
42
- import { createAdapter } from '#internals/runtime/auto.ts';
43
- import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts';
44
- import type { HelpLinks } from './help-links.ts';
45
- import { deriveHelpLinks } from './help-links.ts';
46
- import type { OutputPolicy } from './planner.ts';
47
- import { planInvocation } from './planner.ts';
48
- import type { CLIPlugin } from './plugin.ts';
49
- import { plugin } from './plugin.ts';
50
- import { formatRootHelp } from './root-help.ts';
51
- import { prepareRuntimePreflight } from './runtime-preflight.ts';
52
-
53
- // --- Type-erased command — erasure function (interface now in schema/command.ts)
54
-
55
- function commandRoutes(schema: CommandSchema): readonly string[] {
56
- return [schema.name, ...schema.aliases];
57
- }
58
-
59
- function assertNoSiblingRouteConflict(
60
- parentCommandName: string,
61
- routeOwners: Map<string, string>,
62
- route: string,
63
- commandName: string,
64
- ): void {
65
- const owner = routeOwners.get(route);
66
- if (owner !== undefined) {
67
- throw new CLIError(
68
- `Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`,
69
- {
70
- code: 'DUPLICATE_COMMAND',
71
- suggest: 'Ensure sibling command names and aliases are unique',
72
- },
73
- );
74
- }
75
-
76
- routeOwners.set(route, commandName);
77
- }
78
-
79
- function assertNoTopLevelRouteConflict(
80
- commands: readonly ErasedCommand[],
81
- incoming: CommandSchema,
82
- ): void {
83
- const routeOwners = new Map<string, string>();
84
-
85
- for (const command of commands) {
86
- for (const route of commandRoutes(command.schema)) {
87
- assertNoSiblingRouteConflict('root', routeOwners, route, command.schema.name);
88
- }
89
- }
90
-
91
- for (const route of commandRoutes(incoming)) {
92
- const owner = routeOwners.get(route);
93
- if (owner !== undefined) {
94
- throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
95
- code: 'DUPLICATE_COMMAND',
96
- suggest:
97
- owner === incoming.name
98
- ? `Ensure command '${incoming.name}' does not reuse route '${route}'`
99
- : `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`,
100
- });
101
- }
102
-
103
- routeOwners.set(route, incoming.name);
104
- }
105
- }
106
-
107
- /**
108
- * Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
109
- * building the subcommand tree.
110
- *
111
- * The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
112
- * the original `CommandBuilder<F, A>` — no type assertions needed.\
113
- * Subcommands are recursively erased and indexed by name and alias for
114
- * O(1) lookup during dispatch.
115
- *
116
- * @internal
117
- */
118
- function eraseCommand<
119
- F extends Record<string, FlagBuilder<FlagConfig>>,
120
- A extends Record<string, ArgBuilder<ArgConfig>>,
121
- C extends Record<string, unknown>,
122
- >(cmd: CommandBuilder<F, A, C>): ErasedCommand {
123
- // Recursively erase subcommands, keyed by name and alias.
124
- const subcommands = new Map<string, ErasedCommand>();
125
- const routeOwners = new Map<string, string>();
126
- for (const sub of cmd._subcommands) {
127
- const routes = commandRoutes(sub.schema);
128
- for (const route of routes) {
129
- assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
130
- }
131
-
132
- const erased = eraseCommand(sub);
133
- for (const route of routes) {
134
- subcommands.set(route, erased);
135
- }
136
- }
137
-
138
- return {
139
- schema: cmd.schema,
140
- subcommands,
141
- _command: cmd as unknown as AnyCommandBuilder,
142
- _execute(argv, options) {
143
- return runCommand(cmd, argv, options);
144
- },
145
- };
146
- }
147
-
148
- // --- CLI schema — runtime descriptor for the CLI program
149
-
150
- /**
151
- * Runtime descriptor for the CLI program.
152
- *
153
- * Stores the program name, version, description, and registered commands.\
154
- * Built incrementally by {@linkcode CLIBuilder}.
155
- */
156
- interface CLISchema {
157
- /** Program name (used in help text, usage lines, and completion scripts). */
158
- readonly name: string;
159
- /**
160
- * Whether `.run()` should replace `name` with the invoked program name.
161
- *
162
- * Set via the `cli({ inherit: true })` factory form.
163
- */
164
- readonly inheritName: boolean;
165
- /** Program version (shown by `--version`). */
166
- readonly version: string | undefined;
167
- /** Program description (shown in root help). */
168
- readonly description: string | undefined;
169
- /** Registered commands (type-erased for heterogeneous storage). */
170
- readonly commands: readonly ErasedCommand[];
171
- /**
172
- * Default command dispatched when no subcommand matches.
173
- *
174
- * When set, the CLI root behaves like a hybrid command group: subcommands
175
- * dispatch by name as usual, but empty argv or flags-only argv falls
176
- * through to this command instead of showing root help.
177
- *
178
- * Set via the {@linkcode CLIBuilder.default | .default()} builder method.
179
- */
180
- readonly defaultCommand: ErasedCommand | undefined;
181
- /**
182
- * Config discovery settings.
183
- *
184
- * When defined, {@linkcode CLIBuilder.run | .run()} auto-discovers and loads a config file before command dispatch.
185
- *
186
- * Set via the {@linkcode CLIBuilder.config | .config()} builder method.
187
- */
188
- readonly configSettings: ConfigSettings | undefined;
189
- /**
190
- * Manifest auto-discovery settings. When defined, `.run()` discovers the
191
- * nearest manifest (`package.json`, `deno.json`, `jsr.json`, …) and merges
192
- * metadata before dispatch.
193
- *
194
- * Set via the {@linkcode CLIBuilder.manifest | .manifest()} builder method
195
- * (or the {@linkcode CLIBuilder.packageJson | .packageJson()} /
196
- * {@linkcode CLIBuilder.denoJson | .denoJson()} presets).
197
- */
198
- readonly packageJsonSettings: ResolvedManifestSettings | undefined;
199
- /**
200
- * OSC 8 hyperlink targets for the root-help header (name/version).
201
- *
202
- * Set via the {@linkcode CLIBuilder.links | .links()} builder method.
203
- * Fields left `undefined` are derived from manifest metadata
204
- * (`repository` / `homepage`) when manifest discovery ({@linkcode
205
- * CLIBuilder.manifest | .manifest()}) is active.
206
- */
207
- readonly helpLinks: HelpLinks | undefined;
208
- /** Whether built-in `.completions()` command registration is active. */
209
- readonly hasBuiltInCompletions: boolean;
210
- /** Registered CLI plugins. */
211
- readonly plugins: readonly CLIPlugin[];
212
- }
213
-
214
- /**
215
- * Config discovery settings for automatic config file loading.
216
- *
217
- * Stored in {@link CLISchema} and consumed by {@linkcode CLIBuilder.run()} to call
218
- * {@link discoverConfig} before dispatching to a command.
219
- */
220
- interface ConfigSettings {
221
- /**
222
- * Application name used to build config search paths.
223
- *
224
- * Search paths: `.{appName}.json` (cwd), `{appName}.config.json` (cwd),
225
- * and `{configDir}/{appName}/config.json` where `configDir` is
226
- * `$XDG_CONFIG_HOME` / `~/.config` on Unix or `%APPDATA%` /
227
- * `%USERPROFILE%\\AppData\\Roaming` on Windows.
228
- */
229
- readonly appName: string;
230
-
231
- /** Additional format loaders beyond the built-in JSON loader. */
232
- readonly loaders: readonly FormatLoader[] | undefined;
233
- }
234
-
235
- /**
236
- * Manifest auto-discovery settings — the resolved/normalized shape stored in
237
- * the schema.
238
- *
239
- * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
240
- * call {@link discoverManifest} before dispatching to a command.
241
- *
242
- * Note: the schema FIELD name (`packageJsonSettings`) keeps its `packageJson`
243
- * prefix for backward compatibility — renaming it would break consumers reading
244
- * `app.schema.packageJsonSettings`. The type itself is now generically named
245
- * (it holds discovery config for any manifest — `package.json`, `deno.json`,
246
- * `jsr.json`); the legacy {@link PackageJsonSettings} alias remains exported for
247
- * backward compatibility.
248
- */
249
- interface ResolvedManifestSettings {
250
- /**
251
- * Infer CLI name from manifest `bin` keys or `name` field.
252
- *
253
- * When `true`, the discovered name replaces the `cli(name)` value.
254
- * Explicit `.version()`/`.description()` calls still take precedence
255
- * over discovered values.
256
- *
257
- * @defaultValue `false`
258
- */
259
- readonly inferName: boolean;
260
- /**
261
- * Strip a leading `@scope/` from the inferred `name` fallback.
262
- *
263
- * Only consulted when {@link ResolvedManifestSettings.inferName | `inferName`}
264
- * is `true` and the name comes from the manifest `name` field (not a `bin`
265
- * key, which is never scoped).
266
- *
267
- * @defaultValue `true`
268
- */
269
- readonly stripScope: boolean;
270
- /**
271
- * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
272
- *
273
- * Resolved to a string path before storage. When set, `discoverManifest`
274
- * walks up from here instead of the runtime cwd. Required for installable
275
- * CLIs whose version should reflect THEIR OWN package, not the consumer's
276
- * working directory.
277
- */
278
- readonly from: string | undefined;
279
- /**
280
- * Candidate manifest filenames, in per-directory priority order
281
- * (e.g. `['deno.json', 'deno.jsonc', 'jsr.json']` for `.denoJson()`).
282
- */
283
- readonly files: readonly string[];
284
- /**
285
- * Pre-loaded data; skips filesystem discovery, uses values verbatim.
286
- *
287
- * @example
288
- * ```ts
289
- * import pkg from './package.json' with { type: 'json' };
290
- *
291
- * cli('mycli').manifest(pkg);
292
- * ```
293
- */
294
- readonly data: PackageJsonData | undefined;
295
- }
296
-
297
- /**
298
- * Resolved manifest discovery settings stored in {@link CLISchema}.
299
- *
300
- * @deprecated Renamed to {@link ResolvedManifestSettings}. The stored shape
301
- * holds generic manifest discovery config (`package.json`, `deno.json`,
302
- * `jsr.json`), not just `package.json`; the misleading name is kept only for
303
- * backward compatibility.
304
- */
305
- type PackageJsonSettings = ResolvedManifestSettings;
306
-
307
- // --- Options for execute/run
308
-
309
- /**
310
- * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
311
- *
312
- * Derives from {@linkcode RunOptions} while excluding command-execution internals
313
- * (`meta`, `mergedSchema`) and adding the CLI-level runtime adapter.
314
- */
315
- interface CLIRunOptions extends Omit<RunOptions, 'meta' | 'mergedSchema'> {
316
- /**
317
- * Runtime adapter providing platform-specific I/O, argv, env, etc.
318
- *
319
- * When provided to `.run()`, replaces the default Node adapter.
320
- * Ignored by `.execute()` (which is process-free by design).
321
- */
322
- readonly adapter?: RuntimeAdapter;
323
- }
324
-
325
- // --- Command run options builder
326
-
327
- /**
328
- * Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
329
- * field to satisfy `exactOptionalPropertyTypes`.
330
- *
331
- * @param options - CLI-level run options (may be `undefined` for defaults).
332
- * @param helpOptions - Help formatting options forwarded to commands.
333
- * @param meta - Optional command metadata (omitted for root-level dispatch).
334
- * @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
335
- *
336
- * @internal
337
- */
338
- function buildCommandRunOptions(
339
- options: CLIRunOptions | undefined,
340
- helpOptions: HelpOptions,
341
- meta?: CommandMeta,
342
- ): RunOptions {
343
- return {
344
- help: helpOptions,
345
- ...(meta !== undefined ? { meta } : {}),
346
- ...(options?.plugins !== undefined ? { plugins: options.plugins } : {}),
347
- ...(options?.env !== undefined ? { env: options.env } : {}),
348
- ...(options?.config !== undefined ? { config: options.config } : {}),
349
- ...(options?.stdinData !== undefined ? { stdinData: options.stdinData } : {}),
350
- ...(options?.prompter !== undefined ? { prompter: options.prompter } : {}),
351
- ...(options?.answers !== undefined ? { answers: options.answers } : {}),
352
- ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
353
- ...(options?.jsonMode !== undefined ? { jsonMode: options.jsonMode } : {}),
354
- ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
355
- ...(options?.out !== undefined ? { out: options.out } : {}),
356
- ...(options?.captured !== undefined ? { captured: options.captured } : {}),
357
- };
358
- }
359
-
360
- // --- CLIBuilder — immutable builder for the CLI program
361
-
362
- /**
363
- * Immutable CLI program builder.
364
- *
365
- * Registers commands, handles root-level `--help`/`--version`, and
366
- * dispatches to the matched command based on argv.
367
- *
368
- * Two execution paths:
369
- * - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
370
- * - `.run(options?)` — production entry, reads `process.argv`, exits process
371
- *
372
- * @example
373
- * ```ts
374
- * import { cli, command, flag, arg } from '@kjanat/dreamcli';
375
- *
376
- * const deploy = command('deploy')
377
- * .arg('target', arg.string())
378
- * .flag('force', flag.boolean().alias('f'))
379
- * .action(({ args, flags, out }) => {
380
- * out.log(`Deploying ${args.target}...`);
381
- * });
382
- *
383
- * cli('mycli')
384
- * .version('1.0.0')
385
- * .command(deploy)
386
- * .run();
387
- * ```
388
- */
389
- class CLIBuilder {
390
- /** @internal Runtime schema descriptor. */
391
- readonly schema: CLISchema;
392
-
393
- /** Build a CLIBuilder from a pre-constructed schema descriptor. */
394
- constructor(schema: CLISchema) {
395
- this.schema = schema;
396
- }
397
-
398
- // -- Metadata modifiers --------------------------------------------------
399
-
400
- /**
401
- * Set the program version (shown by `--version`).
402
- *
403
- * @param v - Semantic version string.
404
- * @returns The builder (for chaining).
405
- */
406
- version(v: string): CLIBuilder {
407
- return new CLIBuilder({ ...this.schema, version: v });
408
- }
409
-
410
- /**
411
- * Set the program description (shown in root help).
412
- *
413
- * @param text - Short description displayed in root help output.
414
- * @returns The builder (for chaining).
415
- */
416
- description(text: string): CLIBuilder {
417
- return new CLIBuilder({ ...this.schema, description: text });
418
- }
419
-
420
- /**
421
- * Make the root-help header clickable with OSC 8 hyperlinks.
422
- *
423
- * Links the program name and version on the first line of root `--help`
424
- * output in terminals that support
425
- * [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
426
- * The escapes are only emitted when stdout is a TTY (overridable via
427
- * `options.help.hyperlinks`), and only in the header — usage lines, the
428
- * `--help` hint, the commands table, and completion scripts stay plain.
429
- *
430
- * URLs not provided here are derived from manifest metadata when
431
- * `.manifest()` is active (works with both filesystem discovery and
432
- * pre-loaded data):
433
- * - **name** → normalized `repository` URL, falling back to `homepage`
434
- * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
435
- * GitHub, `{repo}/-/releases/v{version}` on GitLab)
436
- *
437
- * @param links - Explicit URLs; omit to derive everything from the manifest.
438
- * @returns The builder (for chaining).
439
- *
440
- * @example
441
- * ```ts
442
- * // Derive both links from the manifest repository/homepage:
443
- * cli('mycli')
444
- * .manifest()
445
- * .links()
446
- * .run();
447
- *
448
- * // Explicit URLs (no package.json required):
449
- * cli('mycli')
450
- * .version('1.0.0')
451
- * .links({
452
- * name: 'https://github.com/me/mycli',
453
- * version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
454
- * })
455
- * .run();
456
- * ```
457
- */
458
- links(links?: { readonly name?: string | URL; readonly version?: string | URL }): CLIBuilder {
459
- return new CLIBuilder({
460
- ...this.schema,
461
- helpLinks: {
462
- name: toUrlString(links?.name),
463
- version: toUrlString(links?.version),
464
- },
465
- });
466
- }
467
-
468
- /**
469
- * Enable automatic config file discovery.
470
- *
471
- * When enabled, `.run()` probes standard paths before dispatching:
472
- * 1. `$CWD/.{appName}.json`
473
- * 2. `$CWD/{appName}.config.json`
474
- * 3. `$CONFIG_DIR/{appName}/config.json`
475
- * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
476
- * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
477
- *
478
- * The user can override the path via `--config <path>` or `--config=<path>`.
479
- *
480
- * Loaded config feeds into the resolution chain
481
- * (CLI → env → **config** → prompt → default) for flags that
482
- * declare `.config('dotted.path')`.
483
- *
484
- * Has no effect in `.execute()` (which receives config via
485
- * `options.config` directly).
486
- *
487
- * @param appName - Name used to build search paths.
488
- * @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
489
- * @returns The builder (for chaining).
490
- */
491
- config(appName: string, loaders?: readonly FormatLoader[]): CLIBuilder {
492
- return new CLIBuilder({
493
- ...this.schema,
494
- configSettings: {
495
- appName,
496
- loaders,
497
- },
498
- });
499
- }
500
-
501
- /**
502
- * Register a custom config format loader.
503
- *
504
- * Adds a {@link FormatLoader} incrementally — call multiple times to
505
- * register multiple formats. Loaders registered later for the same
506
- * extension override earlier ones.
507
- *
508
- * Requires `.config()` to have been called first (sets the app name).
509
- *
510
- * @param loader - Format loader (or extensions + parse function).
511
- * @returns The builder (for chaining).
512
- *
513
- * @example Bun built-in parsers
514
- * ```ts
515
- * import { configFormat } from '@kjanat/dreamcli';
516
- *
517
- * cli('myapp')
518
- * .config('myapp')
519
- * .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
520
- * .configLoader(configFormat(['toml'], Bun.TOML.parse))
521
- * .run();
522
- * ```
523
- *
524
- * @example npm package parsers
525
- * ```ts
526
- * import { configFormat } from '@kjanat/dreamcli';
527
- * import { parse as parseYaml } from 'yaml';
528
- * import { parse as parseTOML } from '@iarna/toml';
529
- *
530
- * cli('myapp')
531
- * .config('myapp')
532
- * .configLoader(configFormat(['yaml', 'yml'], parseYaml))
533
- * .configLoader(configFormat(['toml'], parseTOML))
534
- * .run();
535
- * ```
536
- */
537
- configLoader(loader: FormatLoader): CLIBuilder {
538
- if (this.schema.configSettings === undefined) {
539
- throw new CLIError('.configLoader() requires .config() to be called first', {
540
- code: 'INVALID_BUILDER_STATE',
541
- suggest: 'Call .config(appName) before .configLoader()',
542
- });
543
- }
544
- const existing = this.schema.configSettings.loaders ?? [];
545
- return new CLIBuilder({
546
- ...this.schema,
547
- configSettings: {
548
- ...this.schema.configSettings,
549
- loaders: [...existing, loader],
550
- },
551
- });
552
- }
553
-
554
- /**
555
- * Enable manifest metadata from pre-loaded data.
556
- *
557
- * Pass an already-imported manifest (`package.json`, `deno.json`, `jsr.json`)
558
- * to skip filesystem discovery entirely — useful for bundled or installable
559
- * CLIs where the version should be locked at build time. The data's
560
- * `version`/`description` are merged into the CLI schema immediately, so this
561
- * form works in **both** `.run()` and `.execute()` (the filesystem-free path).
562
- * Explicit `.version()`/`.description()` calls still take precedence, and the
563
- * data form does not infer the CLI name — `inferName` / `{ scope }` are
564
- * available only on the discovery (settings) form. For a pre-loaded manifest
565
- * whose scoped `name` should drive the CLI name, set the name explicitly via
566
- * `cli(name)` (or call {@link inferCliName} on the data yourself).
567
- *
568
- * Detected by field shape: an object carrying at least one of
569
- * `name`/`version`/`description`/`bin`/`homepage`/`repository`. An empty `{}`
570
- * or a settings-shaped object falls through to the settings overload.
571
- *
572
- * @param data - Pre-loaded manifest metadata.
573
- *
574
- * @example
575
- * ```ts
576
- * import denoCfg from './deno.json' with { type: 'json' };
577
- *
578
- * // No filesystem; works in .run() AND .execute():
579
- * cli('mycli')
580
- * .manifest(denoCfg)
581
- * .command(deploy)
582
- * .run();
583
- * ```
584
- */
585
- manifest(data: PackageJsonData): CLIBuilder;
586
- /**
587
- * Enable automatic manifest metadata discovery.
588
- *
589
- * When enabled, `.run()` walks up from `cwd` (or {@link ManifestSettings.from})
590
- * to find the nearest manifest among {@link ManifestSettings.files} and merges
591
- * its `version`/`description` into the CLI schema. Explicit `.version()` /
592
- * `.description()` calls always take precedence.
593
- *
594
- * Files are parsed as JSON with a JSONC fallback — `package.json`, `deno.json`,
595
- * `jsr.json`, and `deno.jsonc` all qualify, including files with `//` / block
596
- * comments or trailing commas. A file that fails both parses is skipped
597
- * (discovery keeps walking).
598
- *
599
- * Has no effect in `.execute()` (filesystem-free) — use the data overload.
600
- *
601
- * @param settings - Optional settings:
602
- * - `files`: candidate manifest filenames in priority order
603
- * (default `['package.json']`).
604
- * - `inferName`: infer the CLI name from `bin` keys or `name`. Pass
605
- * `{ scope: 'keep' }` to keep a leading `@scope/` (stripped by default).
606
- * - `from`: anchor discovery to a file/URL/path instead of `cwd`. Pass
607
- * `import.meta.url` for installable CLIs that must report THEIR OWN
608
- * version. Accepts string paths, `file:` URL strings, or `URL` instances.
609
- *
610
- * @example
611
- * ```ts
612
- * // Deno CLI: discover OUR deno.json (then jsr.json), keep the scope in name:
613
- * cli('mycli')
614
- * .manifest({
615
- * files: ['deno.json', 'jsr.json'],
616
- * from: import.meta.url,
617
- * inferName: { scope: 'keep' },
618
- * })
619
- * .command(deploy)
620
- * .run();
621
- * ```
622
- */
623
- manifest(settings?: ManifestSettings): CLIBuilder;
624
- manifest(input?: PackageJsonData | ManifestSettings): CLIBuilder {
625
- return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
626
- }
627
-
628
- /**
629
- * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
630
- *
631
- * @deprecated Use {@link CLIBuilder.manifest} — `.manifest()` defaults to
632
- * `package.json` and also supports `deno.json` / `jsr.json` via `files`.
633
- *
634
- * @param data - Pre-loaded `package.json` metadata.
635
- */
636
- packageJson(data: PackageJsonData): CLIBuilder;
637
- /**
638
- * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
639
- *
640
- * @deprecated Use {@link CLIBuilder.manifest}.
641
- *
642
- * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
643
- */
644
- packageJson(settings?: ManifestPresetSettings): CLIBuilder;
645
- packageJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
646
- return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
647
- }
648
-
649
- /**
650
- * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
651
- * {@link CLIBuilder.manifest}).
652
- *
653
- * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
654
- *
655
- * @param data - Pre-loaded `deno.json` / `jsr.json` metadata.
656
- */
657
- denoJson(data: PackageJsonData): CLIBuilder;
658
- /**
659
- * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
660
- * {@link CLIBuilder.manifest}).
661
- *
662
- * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
663
- *
664
- * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
665
- * `deno.json` / `jsr.json` have no `bin` field, so `inferName` resolves
666
- * from `name`; pass `{ scope: 'keep' }` to retain a leading `@scope/`.
667
- *
668
- * @example
669
- * ```ts
670
- * cli('mycli')
671
- * .denoJson({ from: import.meta.url })
672
- * .command(deploy)
673
- * .run();
674
- * ```
675
- */
676
- denoJson(settings?: ManifestPresetSettings): CLIBuilder;
677
- denoJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
678
- return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
679
- }
680
-
681
- // -- Command registration ------------------------------------------------
682
-
683
- /**
684
- * Register a command with the CLI program.
685
- *
686
- * The command's type parameters are erased for heterogeneous storage.
687
- * Type safety is preserved inside the closure that delegates to
688
- * {@linkcode runCommand | runCommand()}.
689
- *
690
- * @param cmd - {@link CommandBuilder} to register.
691
- * @returns The builder (for chaining).
692
- */
693
- command<
694
- F extends Record<string, FlagBuilder<FlagConfig>>,
695
- A extends Record<string, ArgBuilder<ArgConfig>>,
696
- C extends Record<string, unknown>,
697
- >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
698
- assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
699
-
700
- return new CLIBuilder({
701
- ...this.schema,
702
- commands: [...this.schema.commands, eraseCommand(cmd)],
703
- });
704
- }
705
-
706
- /**
707
- * Register a command as the default — dispatched when no subcommand is given.
708
- *
709
- * The CLI root behaves like a hybrid command group: named subcommands
710
- * dispatch normally, but empty argv or flags-only argv falls through to
711
- * this command instead of showing root help.
712
- *
713
- * The command is also registered as a normal subcommand (can be invoked
714
- * by name). Only one default command is allowed.
715
- *
716
- * @example
717
- * ```ts
718
- * // Single-command CLI — no subcommand name needed:
719
- * // mytool --force production
720
- * cli('mytool')
721
- * .default(deploy)
722
- * .run();
723
- *
724
- * // Multi-command CLI with a default:
725
- * // mytool production → runs deploy
726
- * // mytool status → runs status
727
- * cli('mytool')
728
- * .default(deploy)
729
- * .command(status)
730
- * .run();
731
- * ```
732
- *
733
- * @param cmd - {@link CommandBuilder} to register as the default.
734
- * @returns The builder (for chaining).
735
- */
736
- default<
737
- F extends Record<string, FlagBuilder<FlagConfig>>,
738
- A extends Record<string, ArgBuilder<ArgConfig>>,
739
- C extends Record<string, unknown>,
740
- >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
741
- if (this.schema.defaultCommand !== undefined) {
742
- throw new CLIError('Only one default command is allowed', {
743
- code: 'DUPLICATE_DEFAULT',
744
- suggest: 'Call .default() only once when building the CLI',
745
- });
746
- }
747
-
748
- assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
749
-
750
- const erased = eraseCommand(cmd);
751
- return new CLIBuilder({
752
- ...this.schema,
753
- commands: [...this.schema.commands, erased],
754
- defaultCommand: erased,
755
- });
756
- }
757
-
758
- /**
759
- * Register a CLI plugin.
760
- *
761
- * Plugins run in registration order. At each lifecycle stage, all hooks for
762
- * the first plugin run before hooks for the second plugin, and so on.
763
- *
764
- * @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
765
- * @returns The builder (for chaining).
766
- * @see {@link plugin} to construct plugin definitions.
767
- */
768
- plugin(definition: CLIPlugin): CLIBuilder {
769
- return new CLIBuilder({
770
- ...this.schema,
771
- plugins: [...this.schema.plugins, definition],
772
- });
773
- }
774
-
775
- // -- Built-in subcommands ------------------------------------------------
776
-
777
- /**
778
- * Register a built-in `completions` subcommand that generates shell
779
- * completion scripts.
780
- *
781
- * The generated command accepts a `--shell` flag (required, enum of
782
- * all {@link Shell} values) and writes the completion script to stdout
783
- * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
784
- * instead of a generic parse error.
785
- *
786
- * Call this **after** registering all other commands so the completion
787
- * script includes the full command set. The captured schema is a
788
- * snapshot at call time — commands registered after `.completions()`
789
- * will not appear in the generated script. Completion options are also
790
- * captured at call time.
791
- *
792
- * @example
793
- * ```ts
794
- * cli('mycli')
795
- * .version('1.0.0')
796
- * .command(deploy)
797
- * .command(login)
798
- * .completions({ rootMode: 'surface' })
799
- * .run();
800
- * ```
801
- */
802
- completions(options?: CompletionOptions): CLIBuilder {
803
- if (this.schema.hasBuiltInCompletions) {
804
- throw new CLIError('.completions() has already been called', {
805
- code: 'DUPLICATE_COMMAND',
806
- suggest: 'Call .completions() only once when building the CLI',
807
- });
808
- }
809
-
810
- // Capture current schema — includes all commands registered so far.
811
- // The completions command itself is deliberately excluded from the
812
- // generated script (it would be noise in shell completions).
813
- const cliSchema = this.schema;
814
- const completionOptions = options;
815
-
816
- // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
817
- const shellMap = new Map<string, Shell>();
818
- for (const s of SHELLS) shellMap.set(s, s);
819
- shellMap.set('pwsh', 'powershell');
820
-
821
- const cmd = command('completions')
822
- .alias('completion')
823
- .description('Generate shell completion script')
824
- .arg(
825
- 'shell',
826
- arg
827
- .custom((raw: string): Shell => {
828
- // Normalize $SHELL paths across Unix/Windows:
829
- // /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
830
- const segments = raw.split(/[\\/]/);
831
- const basename = segments[segments.length - 1] ?? raw;
832
- const name = basename.replace(/\.(?:exe|cmd|bat)$/i, '');
833
- const shell = shellMap.get(name);
834
- if (shell === undefined) {
835
- throw new Error(`Unknown shell '${name}'. Valid shells: ${SHELLS.join(', ')}`);
836
- }
837
- return shell;
838
- })
839
- .env('SHELL')
840
- .describe(`Target shell (${SHELLS.join(', ')})`),
841
- )
842
- .action(({ args, meta, out }) => {
843
- const completionSchema =
844
- meta.bin === cliSchema.name ? cliSchema : { ...cliSchema, name: meta.bin };
845
- const script = generateCompletion(completionSchema, args.shell, completionOptions);
846
- if (out.jsonMode) {
847
- out.json({ shell: args.shell, script });
848
- } else {
849
- out.log(script);
850
- }
851
- });
852
-
853
- const withCompletions = this.command(cmd);
854
- return new CLIBuilder({
855
- ...withCompletions.schema,
856
- hasBuiltInCompletions: true,
857
- });
858
- }
859
-
860
- // -- Execution -----------------------------------------------------------
861
-
862
- /**
863
- * Execute the CLI program against explicit argv.
864
- *
865
- * This is the testable execution path — no process state is touched.
866
- * Returns a structured {@linkcode RunResult} with exit code and captured output.
867
- *
868
- * @param argv - Raw argv tokens (NOT including the binary/script path,
869
- * i.e. equivalent to `process.argv.slice(2)`).
870
- * @param options - Injectable runtime state.
871
- * @returns Structured result with exit code and captured output.
872
- */
873
- async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
874
- // -- Detect global --json mode before building output ---------------------
875
- // Only a `--json` before the `--` separator toggles JSON mode; a literal
876
- // `--json` positional (after `--`) must reach the command unchanged (#28).
877
- const hasJsonFlag = includesBeforeSeparator(argv, '--json');
878
- const jsonMode = hasJsonFlag || options?.jsonMode === true;
879
-
880
- const captureOptions = {
881
- ...(options?.verbosity !== undefined ? { verbosity: options.verbosity } : {}),
882
- ...(jsonMode ? { jsonMode } : {}),
883
- ...(options?.isTTY !== undefined ? { isTTY: options.isTTY } : {}),
884
- };
885
- let out: Out;
886
- let captured: CapturedOutput;
887
- if (options?.out !== undefined) {
888
- out = options.out;
889
- captured = options.captured ?? { stdout: [], stderr: [], activity: [] };
890
- } else {
891
- [out, captured] = createCaptureOutput(
892
- Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
893
- );
894
- }
895
- clearRequestedExitCode(out);
896
-
897
- // Resolve help options — default binName to CLI program name,
898
- // hyperlinks to TTY detection (escapes never leak into piped output)
899
- const helpOptions: HelpOptions = {
900
- ...options?.help,
901
- binName: options?.help?.binName ?? this.schema.name,
902
- hyperlinks: options?.help?.hyperlinks ?? out.isTTY,
903
- };
904
-
905
- // -- Shared options for command execution ----------------------------------
906
- const effectiveOptions: CLIRunOptions = {
907
- ...options,
908
- plugins: this.schema.plugins,
909
- ...(jsonMode ? { jsonMode } : {}),
910
- };
911
- const output: OutputPolicy = {
912
- jsonMode,
913
- isTTY: out.isTTY,
914
- verbosity: options?.verbosity ?? 'normal',
915
- };
916
- const planned = planInvocation({
917
- schema: this.schema,
918
- argv,
919
- help: helpOptions,
920
- output,
921
- });
922
-
923
- switch (planned.kind) {
924
- case 'root-version':
925
- out.log(planned.version);
926
- return buildRunResult({ exitCode: 0, error: undefined }, captured);
927
-
928
- case 'root-help': {
929
- const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
930
- out.log(helpText);
931
- return buildRunResult({ exitCode: 0, error: undefined }, captured);
932
- }
933
-
934
- case 'dispatch-error': {
935
- if (jsonMode) {
936
- out.json({ error: planned.error.toJSON() });
937
- } else {
938
- out.error(planned.error.message);
939
- if (planned.error.suggest !== undefined && planned.error.code !== 'NO_ACTION') {
940
- out.error(`Suggestion: ${planned.error.suggest}`);
941
- }
942
- }
943
- return buildRunResult({ exitCode: planned.error.exitCode, error: planned.error }, captured);
944
- }
945
-
946
- case 'needs-subcommand': {
947
- const helpText = formatHelp(planned.command.schema, planned.help);
948
- out.log(helpText);
949
- return buildRunResult({ exitCode: 0, error: undefined }, captured);
950
- }
951
-
952
- case 'match': {
953
- const commandRunOptions = buildCommandRunOptions(
954
- effectiveOptions,
955
- planned.plan.help ?? helpOptions,
956
- planned.plan.meta,
957
- );
958
- if (planned.plan.command._command === undefined) {
959
- return planned.plan.command._execute(planned.plan.argv, {
960
- ...commandRunOptions,
961
- mergedSchema: planned.plan.mergedSchema,
962
- });
963
- }
964
- const result = await executeCommand({
965
- command: planned.plan.command._command,
966
- argv: planned.plan.argv,
967
- out,
968
- schema: planned.plan.mergedSchema,
969
- meta: planned.plan.meta,
970
- options: commandRunOptions,
971
- });
972
- return buildRunResult(result, captured);
973
- }
974
- }
975
- }
976
-
977
- /**
978
- * Run the CLI program as a production entry point.
979
- *
980
- * Reads argv from the runtime adapter, dispatches to the matched
981
- * command, writes output to real streams, and exits the process.
982
- *
983
- * This is the **only** place that touches process state (via the
984
- * adapter). For testing, use `.execute()` instead — or provide a
985
- * test adapter via `options.adapter`.
986
- *
987
- * Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
988
- * which auto-detects the runtime (Node.js, Bun) and creates
989
- * the appropriate adapter.
990
- *
991
- * @param options - Optional runtime configuration including adapter.
992
- */
993
- async run(options?: CLIRunOptions): Promise<never> {
994
- const adapter = options?.adapter ?? createAdapter();
995
- const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : undefined;
996
-
997
- const preflight = await prepareRuntimePreflight({
998
- schema: this.schema,
999
- adapter,
1000
- options,
1001
- inheritedName,
1002
- });
1003
-
1004
- if (preflight.kind === 'config-error') {
1005
- if (preflight.jsonMode) {
1006
- adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
1007
- } else {
1008
- adapter.stderr(`Error: ${preflight.error.message}\n`);
1009
- if (preflight.error.suggest !== undefined) {
1010
- adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
1011
- }
1012
- }
1013
- return adapter.exit(preflight.error.exitCode);
1014
- }
1015
-
1016
- const effectiveBuilder =
1017
- preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
1018
- const executeOptions: CLIRunOptions = {
1019
- ...options,
1020
- ...preflight.inputs,
1021
- out: createOutput({
1022
- stdout: adapter.stdout,
1023
- stderr: adapter.stderr,
1024
- jsonMode: preflight.inputs.jsonMode,
1025
- isTTY: preflight.inputs.isTTY,
1026
- ...(preflight.inputs.verbosity !== 'normal'
1027
- ? { verbosity: preflight.inputs.verbosity }
1028
- : {}),
1029
- }),
1030
- };
1031
- const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
1032
-
1033
- // Write captured output to real streams via adapter
1034
- for (const line of result.stdout) {
1035
- adapter.stdout(line);
1036
- }
1037
- for (const line of result.stderr) {
1038
- adapter.stderr(line);
1039
- }
1040
-
1041
- return adapter.exit(result.exitCode);
1042
- }
1043
- }
1044
- const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
1045
-
1046
- /**
1047
- * Extract the final path segment from a path-like or URL-like string.
1048
- *
1049
- * @param input - Forward- or backslash-delimited path.
1050
- * @returns Trailing segment, or `undefined` when the input is empty or slash-only.
1051
- *
1052
- * @internal
1053
- */
1054
- function basename(input: string): string | undefined {
1055
- const trimmed = stripTrailing(input, [SLASH, BACKSLASH]);
1056
- if (trimmed.length === 0) return undefined;
1057
- const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
1058
- const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
1059
- return name.length > 0 ? name : undefined;
1060
- }
1061
-
1062
- /**
1063
- * Detect known interpreter/runtime binary names (node, bun, deno, tsx).
1064
- *
1065
- * @param input - Candidate binary name, with or without `.exe` suffix.
1066
- * @returns `true` when `input` matches a known runtime after normalization.
1067
- *
1068
- * @internal
1069
- */
1070
- function isRuntimeBinaryName(input: string): boolean {
1071
- const normalized = input.toLowerCase().replace(/\.exe$/i, '');
1072
- return RUNTIME_BINARIES.has(normalized);
1073
- }
1074
-
1075
- /**
1076
- * Infer the displayed CLI name from the current runtime invocation.
1077
- *
1078
- * Resolution order:
1079
- * 1. Node/Bun/tsx-style interpreters → script/entry argument basename
1080
- * 2. Standalone executable invocations → argv[0] basename
1081
- * 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
1082
- *
1083
- * @param argv - Full process argv (typically `process.argv` or adapter equivalent).
1084
- * @returns Inferred program name, or `undefined` when inference is ambiguous.
1085
- *
1086
- * @internal
1087
- */
1088
- function inferInvocationName(argv: readonly string[]): string | undefined {
1089
- const argv0 = argv[0];
1090
- const argv1 = argv[1];
1091
- const runtimeName = argv0 !== undefined ? basename(argv0) : undefined;
1092
-
1093
- if (runtimeName !== undefined && isRuntimeBinaryName(runtimeName)) {
1094
- if (runtimeName === 'bun' && argv1 === 'run') {
1095
- const entryArg = argv[2];
1096
- if (entryArg === undefined || entryArg.startsWith('-')) return undefined;
1097
- return basename(entryArg);
1098
- }
1099
- if (runtimeName === 'deno' && argv1 === 'run') return undefined;
1100
- if (argv1 === undefined || argv1.startsWith('-')) return undefined;
1101
- return basename(argv1);
1102
- }
1103
-
1104
- return argv0 !== undefined ? basename(argv0) : undefined;
1105
- }
1106
-
1107
- // --- Help link helpers
1108
-
1109
- /** Coerce a `string | URL` link input to its string form. @internal */
1110
- function toUrlString(value: string | URL | undefined): string | undefined {
1111
- if (value === undefined) return undefined;
1112
- return value instanceof URL ? value.href : value;
1113
- }
1114
-
1115
- /**
1116
- * Resolve derived help links against pre-loaded package.json data.
1117
- *
1118
- * `.run()` resolves links during runtime preflight (where discovered
1119
- * package.json metadata lives); this covers the filesystem-free
1120
- * `.execute()` path, where only the `.packageJson(data)` overload can
1121
- * contribute. Idempotent — already-resolved fields pass through unchanged.
1122
- *
1123
- * @internal
1124
- */
1125
- function resolveHelpLinksSchema(schema: CLISchema): CLISchema {
1126
- if (schema.helpLinks === undefined) return schema;
1127
- return {
1128
- ...schema,
1129
- helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version),
1130
- };
1131
- }
1132
-
1133
- // --- manifest discovery settings
1134
-
1135
- /** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
1136
- const DEFAULT_MANIFEST_FILES: readonly string[] = ['package.json'];
1137
-
1138
- /** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
1139
- const DENO_MANIFEST_FILES: readonly string[] = ['deno.json', 'deno.jsonc', 'jsr.json'];
1140
-
1141
- /**
1142
- * CLI-name inference control for {@link ManifestSettings.inferName}.
1143
- *
1144
- * - `false` (or omitted): do not infer the name.
1145
- * - `true`: infer, stripping a leading `@scope/` from the `name` fallback.
1146
- * - `{ scope: 'keep' }`: infer, keeping the full scoped name.
1147
- * - `{ scope: 'strip' }`: infer, stripping the scope (explicit form of `true`).
1148
- *
1149
- * `scope` is required in the object form: an empty `{}` is rejected so that an
1150
- * options object can never silently enable inference (use `true` for that).
1151
- */
1152
- type InferNameOption = boolean | { readonly scope: 'keep' | 'strip' };
1153
-
1154
- /** Discovery settings accepted by {@link CLIBuilder.manifest}. */
1155
- interface ManifestSettings {
1156
- /** Infer the CLI name from `bin` keys or `name`. @defaultValue `false` */
1157
- readonly inferName?: InferNameOption;
1158
- /** Anchor discovery to a file/URL/path instead of `cwd`. */
1159
- readonly from?: string | URL;
1160
- /**
1161
- * Candidate manifest filenames in priority order — NOT npm's `files` publish
1162
- * globs. Discovery probes each name per directory and takes the first that
1163
- * parses.
1164
- *
1165
- * @defaultValue `['package.json']`
1166
- */
1167
- readonly files?: readonly string[];
1168
- }
1169
-
1170
- /**
1171
- * Discovery settings for the `.packageJson()` / `.denoJson()` presets (no `files`).
1172
- *
1173
- * @deprecated Both presets are deprecated; use {@link ManifestSettings} with
1174
- * {@link CLIBuilder.manifest}.
1175
- */
1176
- type ManifestPresetSettings = Omit<ManifestSettings, 'files'>;
1177
-
1178
- /**
1179
- * Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
1180
- * pair stored in {@link ResolvedManifestSettings}.
1181
- *
1182
- * @internal
1183
- */
1184
- function normalizeInferName(option: InferNameOption | undefined): {
1185
- readonly inferName: boolean;
1186
- readonly stripScope: boolean;
1187
- } {
1188
- if (option === undefined || option === false) return { inferName: false, stripScope: true };
1189
- if (option === true) return { inferName: true, stripScope: true };
1190
- return { inferName: true, stripScope: option.scope !== 'keep' };
1191
- }
1192
-
1193
- /**
1194
- * Build the next {@link CLISchema} for a manifest builder method.
1195
- *
1196
- * Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
1197
- * {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
1198
- * merges `version`/`description` immediately so `.execute()` sees them; the
1199
- * settings overload stores discovery config for runtime preflight.
1200
- *
1201
- * @internal
1202
- */
1203
- function buildManifestSchema(
1204
- schema: CLISchema,
1205
- input: PackageJsonData | ManifestSettings | undefined,
1206
- defaultFiles: readonly string[],
1207
- pinFiles: boolean,
1208
- ): CLISchema {
1209
- if (isPackageJsonData(input)) {
1210
- // Merge data into schema immediately so `.execute()` (which skips runtime
1211
- // preflight) still picks up version/description. Explicit
1212
- // `.version()`/`.description()` calls win, matching settings semantics.
1213
- return {
1214
- ...schema,
1215
- ...(schema.version === undefined && input.version !== undefined
1216
- ? { version: input.version }
1217
- : {}),
1218
- ...(schema.description === undefined && input.description !== undefined
1219
- ? { description: input.description }
1220
- : {}),
1221
- packageJsonSettings: {
1222
- inferName: false,
1223
- stripScope: true,
1224
- from: undefined,
1225
- files: defaultFiles,
1226
- data: input,
1227
- },
1228
- };
1229
- }
1230
- const { inferName, stripScope } = normalizeInferName(input?.inferName);
1231
- // Presets (`pinFiles`) always use their fixed list: the `Omit<…,'files'>` guard
1232
- // only stops fresh literals at compile time, so a `ManifestSettings`-typed
1233
- // variable could otherwise leak `files` through the data-overload dispatch gap.
1234
- const files = pinFiles ? defaultFiles : (input?.files ?? defaultFiles);
1235
- return {
1236
- ...schema,
1237
- packageJsonSettings: {
1238
- inferName,
1239
- stripScope,
1240
- from: normalizeFromSetting(input?.from),
1241
- files,
1242
- data: undefined,
1243
- },
1244
- };
1245
- }
1246
-
1247
- // --- packageJson.from normalisation
1248
-
1249
- /**
1250
- * Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
1251
- * (string path, `file:` URL string, or {@link URL} instance) to a plain
1252
- * filesystem path string. `undefined` passes through unchanged.
1253
- *
1254
- * Runtime-agnostic by design — relies only on the `URL` global (available in
1255
- * every JS runtime) rather than `node:url`, keeping core free of Node
1256
- * built-ins. Non-`file:` inputs are returned unchanged as paths.
1257
- *
1258
- * @internal
1259
- */
1260
- function normalizeFromSetting(from: string | URL | undefined): string | undefined {
1261
- if (from === undefined) return undefined;
1262
- if (from instanceof URL) {
1263
- // Only file: URLs map to a filesystem path; pass others through verbatim.
1264
- if (from.protocol !== 'file:') return from.href;
1265
- } else if (!from.startsWith('file:')) {
1266
- // Plain path (or non-file URL string) — already usable as-is.
1267
- return from;
1268
- }
1269
-
1270
- /*
1271
- * `URL.pathname` strips the `file://` scheme/authority; `decodeURIComponent`
1272
- * resolves percent-escapes. A leading-slash drive letter (`/C:/…`) marks a
1273
- * Windows path — drop the slash and switch to backslashes; otherwise it is a
1274
- * POSIX path already.
1275
- */
1276
- const decoded = decodeURIComponent(new URL(from).pathname);
1277
- if (/^\/[A-Za-z]:/.test(decoded)) {
1278
- return decoded.slice(1).replace(/\//g, '\\');
1279
- }
1280
- return decoded;
1281
- }
1282
-
1283
- /**
1284
- * Predicate distinguishing the {@link PackageJsonData | data} overload of
1285
- * `.packageJson()` from the settings overload at runtime.
1286
- *
1287
- * A value is treated as `PackageJsonData` when it's a plain object that
1288
- * carries at least one recognised field (`name`, `version`, `description`,
1289
- * `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
1290
- * object (`inferName` / `from`) falls through to the settings overload.
1291
- *
1292
- * npm's `files` field (publish globs) is intentionally NOT recognised here, so
1293
- * an object whose only key is `files` routes to the settings overload — where
1294
- * `files` means candidate manifest filenames, never publish globs. Manifests
1295
- * that publish a CLI carry `name`/`version`, so those route to the data overload
1296
- * as expected.
1297
- *
1298
- * Edge case: a metadata-less manifest (e.g. a versionless private-root
1299
- * `package.json` carrying only `files`/`private`) routes to settings, so its
1300
- * `files` would be read as candidate filenames and the object is not stored as
1301
- * data. This is harmless in practice — a metadata-less manifest contributes no
1302
- * `version`/`description` either way — but it means a pre-loaded object must
1303
- * carry real metadata to be honoured as data.
1304
- *
1305
- * @internal
1306
- */
1307
- function isPackageJsonData(value: unknown): value is PackageJsonData {
1308
- if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
1309
- return (
1310
- 'name' in value ||
1311
- 'version' in value ||
1312
- 'description' in value ||
1313
- 'bin' in value ||
1314
- 'homepage' in value ||
1315
- 'repository' in value
1316
- );
1317
- }
1318
-
1319
- // --- Factory function
1320
-
1321
- /**
1322
- * Options for the `cli({...})` factory form.
1323
- *
1324
- * This form is useful when the displayed CLI name should be inferred from the
1325
- * current runtime invocation instead of always being hard-coded.
1326
- */
1327
- interface CLIOptions {
1328
- /**
1329
- * Explicit fallback CLI name.
1330
- *
1331
- * Used by `.execute()`, and by `.run()` when runtime name inheritance is
1332
- * disabled or the invocation name cannot be inferred.
1333
- *
1334
- * @defaultValue `'cli'`
1335
- */
1336
- readonly name?: string;
1337
-
1338
- /**
1339
- * Replace `name` with the invoked program basename during `.run()`.
1340
- *
1341
- * Examples:
1342
- * - `node ./bin/mycli.ts` → `mycli.ts`
1343
- * - `/usr/local/bin/mycli` → `mycli`
1344
- *
1345
- * @defaultValue `false`
1346
- */
1347
- readonly inherit?: boolean;
1348
- }
1349
-
1350
- /**
1351
- * Create a new CLI program builder.
1352
- *
1353
- * The CLI name is used in help text, usage lines, and generated completion scripts.
1354
- *
1355
- * @example
1356
- * ```ts
1357
- * cli('mycli')
1358
- * .version('1.0.0')
1359
- * .description('My awesome tool')
1360
- * .command(deploy)
1361
- * .command(login)
1362
- * .run();
1363
- *
1364
- * cli({ inherit: true })
1365
- * .command(deploy)
1366
- * .run();
1367
- * ```
1368
- */
1369
-
1370
- function cli(name: string): CLIBuilder;
1371
- /** Create a new CLI program builder from an options object. */
1372
- function cli(options: CLIOptions): CLIBuilder;
1373
- function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1374
- const name = typeof nameOrOptions === 'string' ? nameOrOptions : (nameOrOptions.name ?? 'cli');
1375
- const inheritName = typeof nameOrOptions === 'string' ? false : (nameOrOptions.inherit ?? false);
1376
-
1377
- return new CLIBuilder({
1378
- name,
1379
- inheritName,
1380
- version: undefined,
1381
- description: undefined,
1382
- commands: [],
1383
- defaultCommand: undefined,
1384
- configSettings: undefined,
1385
- packageJsonSettings: undefined,
1386
- helpLinks: undefined,
1387
- hasBuiltInCompletions: false,
1388
- plugins: [],
1389
- });
1390
- }
1391
-
1392
- // --- Exports
1393
-
1394
- export type { HelpLinks } from './help-links.ts';
1395
- export type {
1396
- BeforeParseParams,
1397
- CLIPlugin,
1398
- CLIPluginHooks,
1399
- PluginCommandContext,
1400
- ResolvedCommandParams,
1401
- } from './plugin.ts';
1402
- export type {
1403
- CLIOptions,
1404
- CLIRunOptions,
1405
- CLISchema,
1406
- ConfigSettings,
1407
- InferNameOption,
1408
- ManifestPresetSettings,
1409
- ManifestSettings,
1410
- PackageJsonSettings,
1411
- ResolvedManifestSettings,
1412
- };
1413
- export { CLIBuilder, cli, formatRootHelp, plugin };