@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.2

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 (136) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.mjs +7 -1
  66. package/package.json +17 -26
  67. package/src/core/cli/dispatch.ts +0 -355
  68. package/src/core/cli/help-links.ts +0 -82
  69. package/src/core/cli/index.ts +0 -1614
  70. package/src/core/cli/planner.ts +0 -656
  71. package/src/core/cli/plugin.ts +0 -117
  72. package/src/core/cli/propagate.ts +0 -97
  73. package/src/core/cli/root-help.ts +0 -342
  74. package/src/core/cli/root-surface.ts +0 -87
  75. package/src/core/cli/runtime-preflight.ts +0 -456
  76. package/src/core/completion/index.ts +0 -138
  77. package/src/core/completion/shells/bash.ts +0 -459
  78. package/src/core/completion/shells/fish.ts +0 -259
  79. package/src/core/completion/shells/powershell.ts +0 -439
  80. package/src/core/completion/shells/shared.ts +0 -310
  81. package/src/core/completion/shells/zsh.ts +0 -381
  82. package/src/core/config/index.ts +0 -417
  83. package/src/core/config/package-json.ts +0 -560
  84. package/src/core/errors/index.ts +0 -193
  85. package/src/core/execution/index.ts +0 -265
  86. package/src/core/help/ansi.ts +0 -144
  87. package/src/core/help/index.ts +0 -563
  88. package/src/core/json-schema/index.ts +0 -910
  89. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  90. package/src/core/output/activity.ts +0 -575
  91. package/src/core/output/bind.ts +0 -59
  92. package/src/core/output/contracts.ts +0 -194
  93. package/src/core/output/display-value.ts +0 -48
  94. package/src/core/output/index.ts +0 -704
  95. package/src/core/output/renderers.ts +0 -125
  96. package/src/core/output/writer.ts +0 -46
  97. package/src/core/parse/index.ts +0 -742
  98. package/src/core/prompt/index.ts +0 -623
  99. package/src/core/resolve/args.ts +0 -144
  100. package/src/core/resolve/coerce.ts +0 -500
  101. package/src/core/resolve/config.ts +0 -26
  102. package/src/core/resolve/contracts.ts +0 -135
  103. package/src/core/resolve/errors.ts +0 -227
  104. package/src/core/resolve/flags.ts +0 -269
  105. package/src/core/resolve/index.ts +0 -108
  106. package/src/core/resolve/property.ts +0 -99
  107. package/src/core/schema/activity.ts +0 -240
  108. package/src/core/schema/arg.ts +0 -841
  109. package/src/core/schema/command.ts +0 -1500
  110. package/src/core/schema/flag.ts +0 -917
  111. package/src/core/schema/index.ts +0 -96
  112. package/src/core/schema/middleware.ts +0 -171
  113. package/src/core/schema/number-constraints.ts +0 -153
  114. package/src/core/schema/prompt.ts +0 -171
  115. package/src/core/schema/run.ts +0 -198
  116. package/src/core/schema-dsl/index.ts +0 -109
  117. package/src/core/schema-dsl/parse.ts +0 -262
  118. package/src/core/schema-dsl/runtime.ts +0 -609
  119. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  120. package/src/core/testkit/index.ts +0 -147
  121. package/src/index.ts +0 -181
  122. package/src/runtime/adapter.ts +0 -303
  123. package/src/runtime/auto.ts +0 -86
  124. package/src/runtime/bun.ts +0 -48
  125. package/src/runtime/deno.ts +0 -367
  126. package/src/runtime/detect.ts +0 -105
  127. package/src/runtime/index.ts +0 -21
  128. package/src/runtime/node-builtins.d.ts +0 -27
  129. package/src/runtime/node.ts +0 -289
  130. package/src/runtime/paths.ts +0 -64
  131. package/src/runtime/support.ts +0 -77
  132. package/src/runtime.ts +0 -31
  133. package/src/schema.ts +0 -16
  134. package/src/strings.ts +0 -34
  135. package/src/testkit.ts +0 -25
  136. package/src/version.ts +0 -20
@@ -1,656 +0,0 @@
1
- /**
2
- * Internal planner contract for CLI dispatch outcomes.
3
- *
4
- * Captures the stable seam between CLI-facing invocation planning and the
5
- * lower-level execution pipeline. This module is now the explicit invocation
6
- * planner seam: it owns root interception, command dispatch, default-command
7
- * fallback, propagated-flag merging, and match handoff shaping.
8
- *
9
- * @module dreamcli/core/cli/planner
10
- * @internal
11
- */
12
-
13
- import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
14
- import { normalizeShell } from '#internals/core/completion/index.ts';
15
- import { CLIError, ParseError } from '#internals/core/errors/index.ts';
16
- import type { HelpOptions } from '#internals/core/help/index.ts';
17
- import type { OutputPolicy } from '#internals/core/output/contracts.ts';
18
- import {
19
- buildFlagLookup,
20
- flagExpectsValue,
21
- includesBeforeSeparator,
22
- } from '#internals/core/parse/index.ts';
23
- import type { CommandMeta, CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
24
- import { dispatch, findClosestCommand } from './dispatch.ts';
25
- import type { CLIPlugin } from './plugin.ts';
26
- import { collectPropagatedFlags } from './propagate.ts';
27
-
28
- /**
29
- * Structural subset of CLISchema used by the planner.
30
- *
31
- * Decouples invocation planning from the full CLIBuilder surface so the
32
- * planner can be tested and reasoned about without constructing a real CLI.
33
- * @internal
34
- */
35
- interface PlannerSchemaLike {
36
- /** CLI program name used in help text and error messages. */
37
- readonly name: string;
38
- /** Declared version string; `undefined` disables `--version` interception. */
39
- readonly version: string | undefined;
40
- /** Registered top-level commands available for dispatch. */
41
- readonly commands: readonly ErasedCommand[];
42
- /** Fallback command when no subcommand token matches. */
43
- readonly defaultCommand: ErasedCommand | undefined;
44
- /**
45
- * Eager `--completions <shell>` flag configuration, when `.completions()`
46
- * was registered with `{ as: 'flag' }`. `undefined` disables interception.
47
- */
48
- readonly completionsFlag:
49
- | { readonly shells: readonly Shell[]; readonly options: CompletionOptions | undefined }
50
- | undefined;
51
- /** Plugins forwarded into every matched execution plan. */
52
- readonly plugins: readonly CLIPlugin[];
53
- }
54
-
55
- /** Root-level help interception outcome. */
56
- interface RootHelpOutcome {
57
- /** Discriminant — argv matched `--help` / `-h` before any command. */
58
- readonly kind: 'root-help';
59
- /** Help options to render root-level usage. */
60
- readonly help: HelpOptions;
61
- }
62
-
63
- /** Root-level version interception outcome. */
64
- interface RootVersionOutcome {
65
- /** Discriminant — argv matched `--version` / `-V` and schema declares a version. */
66
- readonly kind: 'root-version';
67
- /** Resolved version string to render. */
68
- readonly version: string;
69
- }
70
-
71
- /** Root-level `--completions [shell]` interception outcome. */
72
- interface RootCompletionsOutcome {
73
- /** Discriminant — argv matched the eager `--completions [shell]` flag. */
74
- readonly kind: 'root-completions';
75
- /**
76
- * Resolved, validated target shell, or `undefined` when the flag was given
77
- * without a value and the shell should be auto-detected from the environment.
78
- */
79
- readonly shell: Shell | undefined;
80
- /** Generator options captured at build time. */
81
- readonly options: CompletionOptions | undefined;
82
- }
83
-
84
- /** CLI-level dispatch failure before command execution starts. */
85
- interface DispatchErrorOutcome {
86
- /** Discriminant — dispatch could not resolve a command from argv. */
87
- readonly kind: 'dispatch-error';
88
- /** Structured error with suggestion text for the caller to render. */
89
- readonly error: CLIError;
90
- }
91
-
92
- /** Successful planner handoff to the shared command execution path. */
93
- interface PlannerMatchOutcome {
94
- /** Discriminant — dispatch found a matching command for argv. */
95
- readonly kind: 'match';
96
- /** Fully resolved execution plan ready for the executor pipeline. */
97
- readonly plan: CommandExecutionPlan;
98
- }
99
-
100
- /**
101
- * Stable planner result union for the re-foundation workstream.
102
- *
103
- * `CLIBuilder.execute()` still renders and executes these outcomes, but
104
- * planning itself is intentionally bounded to this union.
105
- */
106
- type DispatchOutcome =
107
- | RootHelpOutcome
108
- | RootVersionOutcome
109
- | RootCompletionsOutcome
110
- | DispatchErrorOutcome
111
- | PlannerMatchOutcome;
112
-
113
- /**
114
- * Concrete execution handoff produced by a successful planner match.
115
- *
116
- * `mergedSchema` is the exact command schema the executor sees after
117
- * propagated ancestor flags are collected and child definitions shadow them.
118
- */
119
- interface CommandExecutionPlan {
120
- /** Type-erased command instance that owns the handler. */
121
- readonly command: ErasedCommand;
122
- /** Command schema with propagated ancestor flags merged in. */
123
- readonly mergedSchema: CommandSchema;
124
- /** Remaining argv tokens after command dispatch consumed the command path. */
125
- readonly argv: readonly string[];
126
- /** CLI-level metadata (program name, bin, version) for the handler context. */
127
- readonly meta: CommandMeta;
128
- /** Plugins to run through the execution lifecycle. */
129
- readonly plugins: readonly CLIPlugin[];
130
- /** Output policy (json mode, TTY, verbosity) governing handler rendering. */
131
- readonly output: OutputPolicy;
132
- /** Help options for rendering per-command help; `undefined` when unavailable. */
133
- readonly help: HelpOptions | undefined;
134
- }
135
-
136
- interface BuildCommandExecutionPlanOptions {
137
- readonly command: ErasedCommand;
138
- readonly commandPath: readonly CommandSchema[];
139
- readonly argv: readonly string[];
140
- readonly meta: CommandMeta;
141
- readonly plugins: readonly CLIPlugin[];
142
- readonly output: OutputPolicy;
143
- readonly help: HelpOptions | undefined;
144
- }
145
-
146
- /**
147
- * Dispatch resolved a group command that requires a subcommand selection.
148
- *
149
- * The caller should render subcommand-level help for the matched group.
150
- * @internal
151
- */
152
- interface NeedsSubcommandOutcome {
153
- /** Discriminant — group command matched but no leaf subcommand was selected. */
154
- readonly kind: 'needs-subcommand';
155
- /** The group command that was matched. */
156
- readonly command: ErasedCommand;
157
- /** Full ancestor path from root to this group, used for propagated flag collection. */
158
- readonly commandPath: readonly CommandSchema[];
159
- /** Help options scoped to the group command's bin path. */
160
- readonly help: HelpOptions;
161
- }
162
-
163
- /** Full planner result including the `needs-subcommand` variant used by CLIBuilder. @internal */
164
- type InvocationPlan = DispatchOutcome | NeedsSubcommandOutcome;
165
-
166
- /** Options bag for {@linkcode planInvocation}. @internal */
167
- interface PlanInvocationOptions {
168
- /** CLI schema subset driving dispatch decisions. */
169
- readonly schema: PlannerSchemaLike;
170
- /** Raw argv tokens (typically `adapter.argv.slice(2)`). */
171
- readonly argv: readonly string[];
172
- /** Root-level help configuration for rendering. */
173
- readonly help: HelpOptions;
174
- /** Output policy propagated into matched execution plans. */
175
- readonly output: OutputPolicy;
176
- }
177
-
178
- function buildMeta(
179
- schema: PlannerSchemaLike,
180
- helpOptions: HelpOptions,
181
- commandName: string,
182
- ): CommandMeta {
183
- return {
184
- name: schema.name,
185
- bin: helpOptions.binName ?? schema.name,
186
- version: schema.version,
187
- command: commandName,
188
- };
189
- }
190
-
191
- /** Build a name+alias lookup map for top-level commands. @internal */
192
- function buildRootCommandMap(
193
- commands: readonly ErasedCommand[],
194
- ): ReadonlyMap<string, ErasedCommand> {
195
- const rootCommands = new Map<string, ErasedCommand>();
196
-
197
- const addRoute = (route: string, command: ErasedCommand): void => {
198
- const existing = rootCommands.get(route);
199
- if (existing !== undefined) {
200
- throw new CLIError(
201
- `Duplicate root command route '${route}' (${existing.schema.name} and ${command.schema.name})`,
202
- {
203
- code: 'DUPLICATE_COMMAND',
204
- suggest: 'Ensure root command names and aliases are unique',
205
- },
206
- );
207
- }
208
-
209
- rootCommands.set(route, command);
210
- };
211
-
212
- for (const cmd of commands) {
213
- addRoute(cmd.schema.name, cmd);
214
- for (const alias of cmd.schema.aliases) {
215
- addRoute(alias, cmd);
216
- }
217
- }
218
- return rootCommands;
219
- }
220
-
221
- /**
222
- * Merge propagated ancestor flags into the matched command schema.
223
- *
224
- * Child flag definitions win when names collide, matching current CLI
225
- * dispatch semantics and the future planner contract.
226
- */
227
- function mergeCommandSchema(
228
- command: ErasedCommand,
229
- commandPath: readonly CommandSchema[],
230
- ): CommandSchema {
231
- const propagated = collectPropagatedFlags(commandPath);
232
- if (Object.keys(propagated).length === 0) {
233
- return command.schema;
234
- }
235
-
236
- return {
237
- ...command.schema,
238
- flags: { ...propagated, ...command.schema.flags },
239
- };
240
- }
241
-
242
- /** Build the planner handoff for a matched command invocation. */
243
- function buildCommandExecutionPlan(
244
- options: BuildCommandExecutionPlanOptions,
245
- ): CommandExecutionPlan {
246
- return {
247
- command: options.command,
248
- mergedSchema: mergeCommandSchema(options.command, options.commandPath),
249
- argv: options.argv,
250
- meta: options.meta,
251
- plugins: options.plugins,
252
- output: options.output,
253
- help: options.help,
254
- };
255
- }
256
-
257
- function buildPlannerMatchOutcome(
258
- schema: PlannerSchemaLike,
259
- command: ErasedCommand,
260
- commandPath: readonly CommandSchema[],
261
- argv: readonly string[],
262
- help: HelpOptions,
263
- output: OutputPolicy,
264
- ): PlannerMatchOutcome {
265
- return {
266
- kind: 'match',
267
- plan: buildCommandExecutionPlan({
268
- command,
269
- commandPath,
270
- argv,
271
- meta: buildMeta(schema, help, command.schema.name),
272
- plugins: schema.plugins,
273
- output,
274
- help,
275
- }),
276
- };
277
- }
278
-
279
- function canDelegateUnknownRootToDefault(command: ErasedCommand, input: string): boolean {
280
- return input === '' || command.schema.args.length > 0;
281
- }
282
-
283
- function findUnknownFlagBeforePositional(
284
- argv: readonly string[],
285
- flags: CommandSchema['flags'],
286
- ): string | undefined {
287
- const lookup = buildFlagLookup(flags);
288
-
289
- for (let index = 0; index < argv.length; index++) {
290
- const token = argv[index];
291
- if (token === undefined || token === '--') return undefined;
292
- if (token === '-' || !token.startsWith('-')) return undefined;
293
-
294
- if (token.startsWith('--')) {
295
- const equalsIndex = token.indexOf('=');
296
- const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
297
- const entry = lookup.get(name);
298
- if (entry === undefined) return equalsIndex === -1 ? token : `--${name}`;
299
- if (equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
300
- continue;
301
- }
302
-
303
- const chars = token.slice(1);
304
- for (let charIndex = 0; charIndex < chars.length; charIndex++) {
305
- const char = chars.charAt(charIndex);
306
- const entry = lookup.get(char);
307
- if (entry === undefined) return `-${char}`;
308
- if (!flagExpectsValue(entry[1])) continue;
309
- if (charIndex === chars.length - 1) index++;
310
- break;
311
- }
312
- }
313
-
314
- return undefined;
315
- }
316
-
317
- /**
318
- * Result of scanning the pre-`--`, `--json`-stripped head for root interception.
319
- * @internal
320
- */
321
- interface RootHeadScan {
322
- /**
323
- * `--help` / `-h` appeared in the head before any command-dispatch token.
324
- *
325
- * Mirrors the global reach of `--version` (#29): a help flag preceded only by
326
- * flags (no subcommand token) is a *root* help request. A help flag that
327
- * follows a subcommand token is left to that command's executor, so
328
- * `app sub --help` still renders the subcommand's help.
329
- */
330
- readonly helpBeforeCommand: boolean;
331
- /** First command-dispatch (positional) token, or `undefined` when the head is all flags. */
332
- readonly firstCommandToken: string | undefined;
333
- /** Index of {@linkcode firstCommandToken} in the head, or `-1` when absent. */
334
- readonly commandTokenIndex: number;
335
- }
336
-
337
- /**
338
- * Scan the pre-`--`, `--json`-stripped head to locate the first command-dispatch
339
- * token and detect a root-level `--help` / `-h` ahead of it.
340
- *
341
- * Value-flag arity is honoured (via `valueFlags`) so a flag value that happens
342
- * to look like a command name is not mistaken for one — matching how
343
- * {@linkcode dispatch} reads the same argv.
344
- *
345
- * @internal
346
- */
347
- function scanRootHead(
348
- head: readonly string[],
349
- valueFlags: ReturnType<typeof buildFlagLookup> | undefined,
350
- ): RootHeadScan {
351
- for (let index = 0; index < head.length; index++) {
352
- const token = head[index];
353
- if (token === undefined) continue;
354
-
355
- if (token === '--help' || token === '-h') {
356
- return { helpBeforeCommand: true, firstCommandToken: undefined, commandTokenIndex: -1 };
357
- }
358
-
359
- // Positional (command-dispatch) token: `-` alone or anything not flag-shaped.
360
- if (token === '-' || !token.startsWith('-')) {
361
- return { helpBeforeCommand: false, firstCommandToken: token, commandTokenIndex: index };
362
- }
363
-
364
- if (token.startsWith('--')) {
365
- const equalsIndex = token.indexOf('=');
366
- const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
367
- const entry = valueFlags?.get(name);
368
- if (entry !== undefined && equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
369
- continue;
370
- }
371
-
372
- // Short-flag cluster: consume a trailing value-expecting flag's argument.
373
- const chars = token.slice(1);
374
- for (let charIndex = 0; charIndex < chars.length; charIndex++) {
375
- const entry = valueFlags?.get(chars.charAt(charIndex));
376
- if (entry === undefined || !flagExpectsValue(entry[1])) continue;
377
- if (charIndex === chars.length - 1) index++;
378
- break;
379
- }
380
- }
381
-
382
- return { helpBeforeCommand: false, firstCommandToken: undefined, commandTokenIndex: -1 };
383
- }
384
-
385
- /**
386
- * Detect and resolve the eager `--completions [shell]` flag before dispatch.
387
- *
388
- * Accepts `--completions <shell>` and `--completions=<shell>`. When no value is
389
- * given (`--completions` alone, or followed by another flag), the shell is left
390
- * `undefined` so the caller can auto-detect it from the environment. Scans only
391
- * before a `--` separator so a literal positional survives.
392
- *
393
- * Returns `undefined` when the flag is absent, a `root-completions` outcome
394
- * otherwise, or a `dispatch-error` when an explicit value names an unknown shell.
395
- *
396
- * @internal
397
- */
398
- function planCompletionsFlag(
399
- argv: readonly string[],
400
- config: { readonly shells: readonly Shell[]; readonly options: CompletionOptions | undefined },
401
- ): RootCompletionsOutcome | DispatchErrorOutcome | undefined {
402
- const separatorIndex = argv.indexOf('--');
403
- const scanEnd = separatorIndex === -1 ? argv.length : separatorIndex;
404
-
405
- for (let index = 0; index < scanEnd; index++) {
406
- const token = argv[index];
407
- if (token === undefined) continue;
408
-
409
- let rawShell: string | undefined;
410
- if (token === '--completions') {
411
- const next = index + 1 < scanEnd ? argv[index + 1] : undefined;
412
- rawShell = next !== undefined && !next.startsWith('-') ? next : undefined;
413
- } else if (token.startsWith('--completions=')) {
414
- rawShell = token.slice('--completions='.length);
415
- } else {
416
- continue;
417
- }
418
-
419
- // No explicit value → defer to environment auto-detection.
420
- if (rawShell === undefined || rawShell === '') {
421
- return { kind: 'root-completions', shell: undefined, options: config.options };
422
- }
423
-
424
- const shell = normalizeShell(rawShell);
425
- if (shell === undefined || !config.shells.includes(shell)) {
426
- return {
427
- kind: 'dispatch-error',
428
- error: new ParseError(`Unknown shell '${rawShell}'`, {
429
- code: 'INVALID_VALUE',
430
- suggest: `Valid shells: ${config.shells.join(', ')}`,
431
- }),
432
- };
433
- }
434
-
435
- return { kind: 'root-completions', shell, options: config.options };
436
- }
437
-
438
- return undefined;
439
- }
440
-
441
- /**
442
- * Decide what to do with an argv invocation before any command executes.
443
- *
444
- * Handles root interception (`--help`, `--version`, `--completions <shell>`,
445
- * bare `help` token), dispatches into the command tree, falls back to the
446
- * default command, and produces structured errors for unknown commands/flags.
447
- * @internal
448
- */
449
- function planInvocation(options: PlanInvocationOptions): InvocationPlan {
450
- // `--json` is a root-level flag, not part of any command schema, so it is
451
- // stripped before dispatch/parse — but only before the `--` separator, so a
452
- // literal `--json` positional (after `--`) survives and reaches the command
453
- // (#28). The `--json` *output mode* is detected separately in `.execute()`.
454
- const separatorIndex = options.argv.indexOf('--');
455
- const head = separatorIndex === -1 ? options.argv : options.argv.slice(0, separatorIndex);
456
- const tail = separatorIndex === -1 ? [] : options.argv.slice(separatorIndex);
457
- const filteredHead = head.includes('--json') ? head.filter((arg) => arg !== '--json') : head;
458
- const filteredArgv = separatorIndex === -1 ? filteredHead : [...filteredHead, ...tail];
459
-
460
- const defaultCommand = options.schema.defaultCommand;
461
- // At the root, a default command's flags govern value-flag arity so a
462
- // space-separated value (`mycli --region eu`) is not misread as a command
463
- // name — both for root interception below and dispatch (see #25).
464
- const rootValueFlags =
465
- defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
466
-
467
- if (
468
- options.schema.version !== undefined &&
469
- (includesBeforeSeparator(options.argv, '--version') ||
470
- includesBeforeSeparator(options.argv, '-V'))
471
- ) {
472
- return {
473
- kind: 'root-version',
474
- version: options.schema.version,
475
- };
476
- }
477
-
478
- if (options.schema.completionsFlag !== undefined) {
479
- const completionsOutcome = planCompletionsFlag(options.argv, options.schema.completionsFlag);
480
- if (completionsOutcome !== undefined) {
481
- return completionsOutcome;
482
- }
483
- }
484
-
485
- // `--help` / `-h` is intercepted at the root with the same positional reach as
486
- // `--version` (#29): a help flag preceded only by flags (no subcommand token)
487
- // is a root request, so `app --verbose --help` mirrors `app --verbose --version`.
488
- // A help flag *after* a subcommand token is left to that command's executor,
489
- // keeping `app sub --help` scoped to the subcommand (version stays global by
490
- // design — there is no per-command version).
491
- const headScan = scanRootHead(filteredHead, rootValueFlags);
492
- if (headScan.helpBeforeCommand) {
493
- return {
494
- kind: 'root-help',
495
- help: options.help,
496
- };
497
- }
498
-
499
- // Bare `help` token: a root help request (or `<command> --help` forwarding)
500
- // when it is the first command token and no real `help` command is registered.
501
- if (headScan.firstCommandToken === 'help') {
502
- const hasRealHelpCommand = options.schema.commands.some(
503
- (command) => command.schema.name === 'help' || command.schema.aliases.includes('help'),
504
- );
505
- if (!hasRealHelpCommand) {
506
- const rest = filteredArgv.slice(headScan.commandTokenIndex + 1);
507
- if (rest.length === 0) {
508
- return {
509
- kind: 'root-help',
510
- help: options.help,
511
- };
512
- }
513
-
514
- return planInvocation({
515
- ...options,
516
- argv: [...rest, '--help'],
517
- });
518
- }
519
- }
520
-
521
- // A CLI with no commands and no default is misconfigured: report NO_ACTION
522
- // even for a bare invocation, rather than masking it with empty root help.
523
- if (options.schema.commands.length === 0 && defaultCommand === undefined) {
524
- return {
525
- kind: 'dispatch-error',
526
- error: new CLIError('No commands registered', {
527
- code: 'NO_ACTION',
528
- suggest: 'Add commands via .command() or .default() before calling .run()',
529
- }),
530
- };
531
- }
532
-
533
- if (filteredArgv.length === 0 && defaultCommand === undefined) {
534
- return {
535
- kind: 'root-help',
536
- help: options.help,
537
- };
538
- }
539
-
540
- const result = dispatch(
541
- filteredArgv,
542
- buildRootCommandMap(options.schema.commands),
543
- [],
544
- rootValueFlags,
545
- );
546
-
547
- switch (result.kind) {
548
- case 'unknown': {
549
- if (defaultCommand !== undefined && result.parentPath.length === 0) {
550
- const suggestion =
551
- result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
552
- if (
553
- suggestion === undefined &&
554
- canDelegateUnknownRootToDefault(defaultCommand, result.input)
555
- ) {
556
- return buildPlannerMatchOutcome(
557
- options.schema,
558
- defaultCommand,
559
- [defaultCommand.schema],
560
- filteredArgv,
561
- options.help,
562
- options.output,
563
- );
564
- }
565
-
566
- const unknownFlag = findUnknownFlagBeforePositional(
567
- filteredArgv,
568
- defaultCommand.schema.flags,
569
- );
570
- if (unknownFlag !== undefined) {
571
- return {
572
- kind: 'dispatch-error',
573
- error: new ParseError(`Unknown flag ${unknownFlag}`, {
574
- code: 'UNKNOWN_FLAG',
575
- suggest: `Run '${options.schema.name} --help' for available commands`,
576
- }),
577
- };
578
- }
579
- }
580
-
581
- if (result.input === '') {
582
- const unknownFlag = filteredArgv.find((token) => token.startsWith('-'));
583
- if (unknownFlag === undefined) {
584
- return {
585
- kind: 'root-help',
586
- help: options.help,
587
- };
588
- }
589
-
590
- return {
591
- kind: 'dispatch-error',
592
- error: new ParseError(`Unknown flag ${unknownFlag}`, {
593
- code: 'UNKNOWN_FLAG',
594
- suggest: `Run '${options.schema.name} --help' for available commands`,
595
- }),
596
- };
597
- }
598
-
599
- const suggestion = findClosestCommand(result.input, result.candidates);
600
- const scopePath =
601
- result.parentPath.length > 0
602
- ? `${options.schema.name} ${result.parentPath.map((schema) => schema.name).join(' ')}`
603
- : options.schema.name;
604
-
605
- return {
606
- kind: 'dispatch-error',
607
- error: new ParseError(`Unknown command: ${result.input}`, {
608
- code: 'UNKNOWN_COMMAND',
609
- suggest:
610
- suggestion !== undefined
611
- ? `Did you mean '${suggestion}'?`
612
- : `Run '${scopePath} --help' for available commands`,
613
- }),
614
- };
615
- }
616
-
617
- case 'needs-subcommand': {
618
- const ancestorNames = result.commandPath.slice(0, -1).map((schema) => schema.name);
619
- return {
620
- kind: 'needs-subcommand',
621
- command: result.command,
622
- commandPath: result.commandPath,
623
- help: {
624
- ...options.help,
625
- binName: [options.schema.name, ...ancestorNames].join(' '),
626
- },
627
- };
628
- }
629
-
630
- case 'match':
631
- return buildPlannerMatchOutcome(
632
- options.schema,
633
- result.command,
634
- result.commandPath,
635
- result.remainingArgv,
636
- options.help,
637
- options.output,
638
- );
639
- }
640
- }
641
-
642
- export type {
643
- CommandExecutionPlan,
644
- DispatchErrorOutcome,
645
- DispatchOutcome,
646
- InvocationPlan,
647
- NeedsSubcommandOutcome,
648
- OutputPolicy,
649
- PlanInvocationOptions,
650
- PlannerMatchOutcome,
651
- PlannerSchemaLike,
652
- RootCompletionsOutcome,
653
- RootHelpOutcome,
654
- RootVersionOutcome,
655
- };
656
- export { buildCommandExecutionPlan, buildRootCommandMap, mergeCommandSchema, planInvocation };