@kjanat/dreamcli 2.4.1 → 3.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/README.md +14 -7
  3. package/dist/core/cli/index.d.mts +283 -81
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +31 -5
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/config/index.d.mts +2 -2
  18. package/dist/core/config/package-json.d.mts +93 -20
  19. package/dist/core/config/package-json.mjs +3 -1
  20. package/dist/core/help/index.d.mts +45 -1
  21. package/dist/core/help/index.mjs +6 -6
  22. package/dist/core/json-schema/index.mjs +1 -1
  23. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  24. package/dist/core/parse/index.d.mts +15 -1
  25. package/dist/core/parse/index.mjs +1 -1
  26. package/dist/core/prompt/index.d.mts +11 -3
  27. package/dist/core/prompt/index.mjs +3 -3
  28. package/dist/core/resolve/coerce.mjs +1 -1
  29. package/dist/core/resolve/flags.mjs +1 -1
  30. package/dist/core/resolve/property.d.mts +2 -0
  31. package/dist/core/resolve/property.mjs +1 -1
  32. package/dist/core/schema/arg.d.mts +90 -10
  33. package/dist/core/schema/arg.mjs +1 -1
  34. package/dist/core/schema/command.d.mts +3 -1
  35. package/dist/core/schema/flag.d.mts +92 -2
  36. package/dist/core/schema/flag.mjs +1 -1
  37. package/dist/core/schema/index.d.mts +2 -1
  38. package/dist/core/schema/number-constraints.d.mts +96 -0
  39. package/dist/core/schema/number-constraints.mjs +1 -0
  40. package/dist/core/schema/prompt.d.mts +15 -0
  41. package/dist/core/schema/run.d.mts +4 -4
  42. package/dist/core/testkit/index.d.mts +9 -5
  43. package/dist/core/testkit/index.mjs +1 -1
  44. package/dist/index.d.mts +4 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/runtime/auto.mjs +1 -1
  47. package/dist/runtime/bun.mjs +1 -1
  48. package/dist/runtime/deno.mjs +2 -2
  49. package/dist/runtime/node.mjs +2 -2
  50. package/dist/version.mjs +1 -1
  51. package/examples/basic.ts +5 -1
  52. package/examples/gh/package.json +2 -7
  53. package/examples/pwsh-demo/package.json +1 -7
  54. package/examples/pwsh-demo/src/main.test.ts +1 -4
  55. package/examples/pwsh-demo/src/main.ts +14 -4
  56. package/examples/transport-launcher.ts +85 -0
  57. package/package.json +15 -24
  58. package/src/core/cli/dispatch.ts +7 -1
  59. package/src/core/cli/index.ts +521 -122
  60. package/src/core/cli/planner.ts +192 -23
  61. package/src/core/cli/root-help.ts +195 -105
  62. package/src/core/cli/root-surface.ts +25 -12
  63. package/src/core/cli/runtime-preflight.ts +43 -8
  64. package/src/core/completion/index.ts +50 -0
  65. package/src/core/completion/shells/powershell.ts +2 -2
  66. package/src/core/completion/shells/shared.ts +30 -3
  67. package/src/core/config/index.ts +12 -2
  68. package/src/core/config/package-json.ts +250 -41
  69. package/src/core/execution/index.ts +1 -4
  70. package/src/core/help/index.ts +57 -10
  71. package/src/core/json-schema/index.ts +23 -4
  72. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  73. package/src/core/parse/index.ts +62 -1
  74. package/src/core/prompt/index.ts +54 -14
  75. package/src/core/resolve/coerce.ts +73 -5
  76. package/src/core/resolve/flags.ts +14 -0
  77. package/src/core/resolve/property.ts +4 -4
  78. package/src/core/schema/arg.ts +125 -3
  79. package/src/core/schema/command.ts +3 -1
  80. package/src/core/schema/flag.ts +120 -4
  81. package/src/core/schema/index.ts +5 -0
  82. package/src/core/schema/number-constraints.ts +153 -0
  83. package/src/core/schema/prompt.ts +15 -0
  84. package/src/core/schema/run.ts +4 -4
  85. package/src/core/testkit/index.ts +32 -8
  86. package/src/index.ts +8 -0
  87. package/src/runtime/auto.ts +0 -24
  88. package/src/runtime/bun.ts +0 -7
  89. package/src/runtime/deno.ts +0 -2
  90. package/src/runtime/node.ts +0 -11
  91. package/src/runtime/support.ts +1 -59
  92. package/src/schema.ts +16 -0
  93. package/dist/runtime/support.d.mts +0 -42
  94. package/dist/runtime/support.mjs +0 -1
@@ -10,7 +10,12 @@
10
10
  */
11
11
 
12
12
  import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
- import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
13
+ import {
14
+ detectShell,
15
+ generateCompletion,
16
+ normalizeShell,
17
+ SHELLS,
18
+ } from '#internals/core/completion/index.ts';
14
19
  import type { FormatLoader } from '#internals/core/config/index.ts';
15
20
  import type { PackageJsonData } from '#internals/core/config/package-json.ts';
16
21
  import { CLIError } from '#internals/core/errors/index.ts';
@@ -36,6 +41,7 @@ import type {
36
41
  } from '#internals/core/schema/command.ts';
37
42
  import { command } from '#internals/core/schema/command.ts';
38
43
  import type { FlagBuilder, FlagConfig } from '#internals/core/schema/flag.ts';
44
+ import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
39
45
  import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
40
46
  import { runCommand } from '#internals/core/testkit/index.ts';
41
47
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
@@ -52,6 +58,48 @@ import { prepareRuntimePreflight } from './runtime-preflight.ts';
52
58
 
53
59
  // --- Type-erased command — erasure function (interface now in schema/command.ts)
54
60
 
61
+ /** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
62
+ const COMPLETIONS_FLAG_NAME = 'completions';
63
+
64
+ /**
65
+ * Whether a command — or any of its nested subcommands — declares a flag that
66
+ * collides with the eager `--completions` flag, by canonical name or long alias.
67
+ *
68
+ * @internal
69
+ */
70
+ function commandReservesCompletionsFlag(schema: CommandSchema): boolean {
71
+ if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
72
+ for (const flagSchema of Object.values(schema.flags)) {
73
+ if (
74
+ getFlagAliasNames(flagSchema, { kind: 'long', includeHidden: true }).includes(
75
+ COMPLETIONS_FLAG_NAME,
76
+ )
77
+ ) {
78
+ return true;
79
+ }
80
+ }
81
+ return schema.commands.some(commandReservesCompletionsFlag);
82
+ }
83
+
84
+ /**
85
+ * Reject a command whose flags would be shadowed by the eager `--completions`
86
+ * flag once `.completions({ as: 'flag' })` is active. Because the planner
87
+ * intercepts `--completions` before dispatch, such a flag could never be reached.
88
+ *
89
+ * @internal
90
+ */
91
+ function assertNoCompletionsFlagCollision(schema: CommandSchema): void {
92
+ if (commandReservesCompletionsFlag(schema)) {
93
+ throw new CLIError(
94
+ `Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`,
95
+ {
96
+ code: 'RESERVED_FLAG',
97
+ suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`,
98
+ },
99
+ );
100
+ }
101
+ }
102
+
55
103
  function commandRoutes(schema: CommandSchema): readonly string[] {
56
104
  return [schema.name, ...schema.aliases];
57
105
  }
@@ -79,10 +127,12 @@ function assertNoSiblingRouteConflict(
79
127
  function assertNoTopLevelRouteConflict(
80
128
  commands: readonly ErasedCommand[],
81
129
  incoming: CommandSchema,
130
+ defaultCommand?: ErasedCommand | undefined,
82
131
  ): void {
83
132
  const routeOwners = new Map<string, string>();
84
133
 
85
- for (const command of commands) {
134
+ const existing = defaultCommand !== undefined ? [...commands, defaultCommand] : commands;
135
+ for (const command of existing) {
86
136
  for (const route of commandRoutes(command.schema)) {
87
137
  assertNoSiblingRouteConflict('root', routeOwners, route, command.schema.name);
88
138
  }
@@ -187,26 +237,94 @@ interface CLISchema {
187
237
  */
188
238
  readonly configSettings: ConfigSettings | undefined;
189
239
  /**
190
- * Package.json auto-discovery settings. When defined, `.run()` discovers
191
- * the nearest `package.json` and merges metadata before dispatch.
240
+ * Manifest auto-discovery settings. When defined, `.run()` discovers the
241
+ * nearest manifest (`package.json`, `deno.json`, `jsr.json`, …) and merges
242
+ * metadata before dispatch.
192
243
  *
193
- * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
244
+ * Set via the {@linkcode CLIBuilder.manifest | .manifest()} builder method
245
+ * (or the {@linkcode CLIBuilder.packageJson | .packageJson()} /
246
+ * {@linkcode CLIBuilder.denoJson | .denoJson()} presets).
194
247
  */
195
- readonly packageJsonSettings: PackageJsonSettings | undefined;
248
+ readonly packageJsonSettings: ResolvedManifestSettings | undefined;
196
249
  /**
197
250
  * OSC 8 hyperlink targets for the root-help header (name/version).
198
251
  *
199
252
  * Set via the {@linkcode CLIBuilder.links | .links()} builder method.
200
- * Fields left `undefined` are derived from package.json metadata
201
- * (`repository` / `homepage`) when `.packageJson()` is active.
253
+ * Fields left `undefined` are derived from manifest metadata
254
+ * (`repository` / `homepage`) when manifest discovery ({@linkcode
255
+ * CLIBuilder.manifest | .manifest()}) is active.
202
256
  */
203
257
  readonly helpLinks: HelpLinks | undefined;
204
- /** Whether built-in `.completions()` command registration is active. */
258
+ /** Whether built-in `.completions()` registration (command or flag) is active. */
205
259
  readonly hasBuiltInCompletions: boolean;
260
+ /**
261
+ * Eager `--completions <shell>` flag configuration.
262
+ *
263
+ * Set when `.completions({ as: 'flag' })` is used instead of the default
264
+ * `completions` subcommand. When defined, the planner intercepts
265
+ * `--completions <shell>` before dispatch, prints the script, and exits;
266
+ * root help advertises the flag in its `Flags:` section.
267
+ */
268
+ readonly completionsFlag: CompletionsFlagConfig | undefined;
269
+ /**
270
+ * Consumer-configured root-help defaults.
271
+ *
272
+ * Set via the {@linkcode CLIBuilder.help | .help()} builder method and merged
273
+ * under runtime `options.help` (runtime wins) before rendering.
274
+ */
275
+ readonly helpConfig: HelpConfig | undefined;
206
276
  /** Registered CLI plugins. */
207
277
  readonly plugins: readonly CLIPlugin[];
208
278
  }
209
279
 
280
+ /**
281
+ * Configuration for the eager `--completions <shell>` flag.
282
+ *
283
+ * Stored in {@link CLISchema} when `.completions({ as: 'flag' })` is used.
284
+ *
285
+ * @internal
286
+ */
287
+ interface CompletionsFlagConfig {
288
+ /** Shell targets the flag accepts (mirrors {@link SHELLS}). */
289
+ readonly shells: readonly Shell[];
290
+ /** Generator options captured at build time (e.g. `functionPrefix`, `rootMode`). */
291
+ readonly options: CompletionOptions | undefined;
292
+ }
293
+
294
+ /**
295
+ * Consumer-facing root-help configuration set via {@linkcode CLIBuilder.help}.
296
+ *
297
+ * Every field is optional; unset fields fall back to built-in defaults and may
298
+ * be overridden per call through runtime `options.help`.
299
+ */
300
+ interface HelpConfig {
301
+ /**
302
+ * Render the default command's arguments and flags inline at the root.
303
+ *
304
+ * @defaultValue `true`
305
+ */
306
+ readonly inlineDefault?: boolean;
307
+ /**
308
+ * Also list the default command in the root `Commands:` table.
309
+ *
310
+ * By default the default command is the root surface and is omitted from the
311
+ * command list (its args/flags render inline instead).
312
+ *
313
+ * @defaultValue `false`
314
+ */
315
+ readonly showDefaultInCommands?: boolean;
316
+ /**
317
+ * Show the `Run '<bin> <command> --help' for more information.` hint.
318
+ *
319
+ * Defaults to showing the hint only when visible subcommands exist.
320
+ */
321
+ readonly footer?: boolean;
322
+ /** Maximum line width (columns). */
323
+ readonly width?: number;
324
+ /** Emit OSC 8 hyperlinks in the header when supported. */
325
+ readonly hyperlinks?: boolean;
326
+ }
327
+
210
328
  /**
211
329
  * Config discovery settings for automatic config file loading.
212
330
  *
@@ -229,14 +347,22 @@ interface ConfigSettings {
229
347
  }
230
348
 
231
349
  /**
232
- * Package.json auto-discovery settings.
350
+ * Manifest auto-discovery settings — the resolved/normalized shape stored in
351
+ * the schema.
233
352
  *
234
353
  * Stored in {@link CLISchema} and consumed by `CLIBuilder.run()` to
235
- * call {@link discoverPackageJson} before dispatching to a command.
354
+ * call {@link discoverManifest} before dispatching to a command.
355
+ *
356
+ * Note: the schema FIELD name (`packageJsonSettings`) keeps its `packageJson`
357
+ * prefix for backward compatibility — renaming it would break consumers reading
358
+ * `app.schema.packageJsonSettings`. The type itself is now generically named
359
+ * (it holds discovery config for any manifest — `package.json`, `deno.json`,
360
+ * `jsr.json`); the legacy {@link PackageJsonSettings} alias remains exported for
361
+ * backward compatibility.
236
362
  */
237
- interface PackageJsonSettings {
363
+ interface ResolvedManifestSettings {
238
364
  /**
239
- * Infer CLI name from package.json `bin` keys or `name` field.
365
+ * Infer CLI name from manifest `bin` keys or `name` field.
240
366
  *
241
367
  * When `true`, the discovered name replaces the `cli(name)` value.
242
368
  * Explicit `.version()`/`.description()` calls still take precedence
@@ -245,15 +371,30 @@ interface PackageJsonSettings {
245
371
  * @defaultValue `false`
246
372
  */
247
373
  readonly inferName: boolean;
374
+ /**
375
+ * Strip a leading `@scope/` from the inferred `name` fallback.
376
+ *
377
+ * Only consulted when {@link ResolvedManifestSettings.inferName | `inferName`}
378
+ * is `true` and the name comes from the manifest `name` field (not a `bin`
379
+ * key, which is never scoped).
380
+ *
381
+ * @defaultValue `true`
382
+ */
383
+ readonly stripScope: boolean;
248
384
  /**
249
385
  * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
250
386
  *
251
- * Resolved to a string path before storage. When set, `discoverPackageJson`
387
+ * Resolved to a string path before storage. When set, `discoverManifest`
252
388
  * walks up from here instead of the runtime cwd. Required for installable
253
389
  * CLIs whose version should reflect THEIR OWN package, not the consumer's
254
390
  * working directory.
255
391
  */
256
392
  readonly from: string | undefined;
393
+ /**
394
+ * Candidate manifest filenames, in per-directory priority order
395
+ * (e.g. `['deno.json', 'deno.jsonc', 'jsr.json']` for `.denoJson()`).
396
+ */
397
+ readonly files: readonly string[];
257
398
  /**
258
399
  * Pre-loaded data; skips filesystem discovery, uses values verbatim.
259
400
  *
@@ -261,12 +402,22 @@ interface PackageJsonSettings {
261
402
  * ```ts
262
403
  * import pkg from './package.json' with { type: 'json' };
263
404
  *
264
- * cli('mycli').packageJson(pkg);
405
+ * cli('mycli').manifest(pkg);
265
406
  * ```
266
407
  */
267
408
  readonly data: PackageJsonData | undefined;
268
409
  }
269
410
 
411
+ /**
412
+ * Resolved manifest discovery settings stored in {@link CLISchema}.
413
+ *
414
+ * @deprecated Renamed to {@link ResolvedManifestSettings}. The stored shape
415
+ * holds generic manifest discovery config (`package.json`, `deno.json`,
416
+ * `jsr.json`), not just `package.json`; the misleading name is kept only for
417
+ * backward compatibility.
418
+ */
419
+ type PackageJsonSettings = ResolvedManifestSettings;
420
+
270
421
  // --- Options for execute/run
271
422
 
272
423
  /**
@@ -390,21 +541,21 @@ class CLIBuilder {
390
541
  * `options.help.hyperlinks`), and only in the header — usage lines, the
391
542
  * `--help` hint, the commands table, and completion scripts stay plain.
392
543
  *
393
- * URLs not provided here are derived from package.json metadata when
394
- * `.packageJson()` is active (works with both filesystem discovery and
544
+ * URLs not provided here are derived from manifest metadata when
545
+ * `.manifest()` is active (works with both filesystem discovery and
395
546
  * pre-loaded data):
396
547
  * - **name** → normalized `repository` URL, falling back to `homepage`
397
548
  * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
398
549
  * GitHub, `{repo}/-/releases/v{version}` on GitLab)
399
550
  *
400
- * @param links - Explicit URLs; omit to derive everything from package.json.
551
+ * @param links - Explicit URLs; omit to derive everything from the manifest.
401
552
  * @returns The builder (for chaining).
402
553
  *
403
554
  * @example
404
555
  * ```ts
405
- * // Derive both links from package.json repository/homepage:
556
+ * // Derive both links from the manifest repository/homepage:
406
557
  * cli('mycli')
407
- * .packageJson()
558
+ * .manifest()
408
559
  * .links()
409
560
  * .run();
410
561
  *
@@ -428,6 +579,31 @@ class CLIBuilder {
428
579
  });
429
580
  }
430
581
 
582
+ /**
583
+ * Configure root-help rendering defaults.
584
+ *
585
+ * Stored on the schema and merged **under** any runtime `options.help`
586
+ * (runtime wins). Call multiple times to set fields incrementally.
587
+ *
588
+ * @param config - Help rendering options (see {@link HelpConfig}).
589
+ * @returns The builder (for chaining).
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * // Echo the default command under Commands and never show the footer:
594
+ * cli('mycli')
595
+ * .help({ showDefaultInCommands: true, footer: false })
596
+ * .default(serve)
597
+ * .run();
598
+ * ```
599
+ */
600
+ help(config: HelpConfig): CLIBuilder {
601
+ return new CLIBuilder({
602
+ ...this.schema,
603
+ helpConfig: { ...this.schema.helpConfig, ...config },
604
+ });
605
+ }
606
+
431
607
  /**
432
608
  * Enable automatic config file discovery.
433
609
  *
@@ -515,106 +691,130 @@ class CLIBuilder {
515
691
  }
516
692
 
517
693
  /**
518
- * Enable package.json metadata from pre-loaded data.
519
- *
520
- * Pass an already-imported `package.json` to skip filesystem discovery
521
- * entirely — useful for bundled or installable CLIs where the version
522
- * should be locked at build time. The data's `version`/`description` are
523
- * merged into the CLI schema immediately, so this form works in **both**
524
- * `.run()` and `.execute()` (the filesystem-free path). Explicit
525
- * `.version()`/`.description()` calls still take precedence, and the data
526
- * form does not infer the CLI name.
694
+ * Enable manifest metadata from pre-loaded data.
695
+ *
696
+ * Pass an already-imported manifest (`package.json`, `deno.json`, `jsr.json`)
697
+ * to skip filesystem discovery entirely — useful for bundled or installable
698
+ * CLIs where the version should be locked at build time. The data's
699
+ * `version`/`description` are merged into the CLI schema immediately, so this
700
+ * form works in **both** `.run()` and `.execute()` (the filesystem-free path).
701
+ * Explicit `.version()`/`.description()` calls still take precedence, and the
702
+ * data form does not infer the CLI name — `inferName` / `{ scope }` are
703
+ * available only on the discovery (settings) form. For a pre-loaded manifest
704
+ * whose scoped `name` should drive the CLI name, set the name explicitly via
705
+ * `cli(name)` (or call {@link inferCliName} on the data yourself).
527
706
  *
528
707
  * Detected by field shape: an object carrying at least one of
529
- * `name`/`version`/`description`/`bin`. An empty `{}` or a settings-shaped
530
- * object falls through to the settings overload.
708
+ * `name`/`version`/`description`/`bin`/`homepage`/`repository`. An empty `{}`
709
+ * or a settings-shaped object falls through to the settings overload.
531
710
  *
532
- * @param data - Pre-loaded `package.json` metadata.
711
+ * @param data - Pre-loaded manifest metadata.
533
712
  *
534
713
  * @example
535
714
  * ```ts
536
- * import pkg from './package.json' with { type: 'json' };
715
+ * import denoCfg from './deno.json' with { type: 'json' };
537
716
  *
538
717
  * // No filesystem; works in .run() AND .execute():
539
718
  * cli('mycli')
540
- * .packageJson(pkg)
719
+ * .manifest(denoCfg)
541
720
  * .command(deploy)
542
721
  * .run();
543
722
  * ```
544
723
  */
545
- packageJson(data: PackageJsonData): CLIBuilder;
724
+ manifest(data: PackageJsonData): CLIBuilder;
546
725
  /**
547
- * Enable automatic package.json metadata discovery.
726
+ * Enable automatic manifest metadata discovery.
548
727
  *
549
- * When enabled, `.run()` walks up from `cwd` to find the nearest
550
- * `package.json` and merges its `version` and `description` fields
551
- * into the CLI schema. Explicit `.version()` and `.description()`
552
- * calls always take precedence over discovered values.
728
+ * When enabled, `.run()` walks up from `cwd` (or {@link ManifestSettings.from})
729
+ * to find the nearest manifest among {@link ManifestSettings.files} and merges
730
+ * its `version`/`description` into the CLI schema. Explicit `.version()` /
731
+ * `.description()` calls always take precedence.
553
732
  *
554
- * Has no effect in `.execute()` (which is filesystem-free by design) —
555
- * use the {@link CLIBuilder.packageJson | data overload} for that.
733
+ * Files are parsed as JSON with a JSONC fallback — `package.json`, `deno.json`,
734
+ * `jsr.json`, and `deno.jsonc` all qualify, including files with `//` / block
735
+ * comments or trailing commas. A file that fails both parses is skipped
736
+ * (discovery keeps walking).
737
+ *
738
+ * Has no effect in `.execute()` (filesystem-free) — use the data overload.
556
739
  *
557
740
  * @param settings - Optional settings:
558
- * - `inferName`: also infer the CLI name from `bin` keys or `name` field.
559
- * - `from`: anchor discovery to a specific file/URL/path instead of `cwd`.
560
- * Pass `import.meta.url` for installable CLIs that need to report
561
- * THEIR OWN version (not the consumer's project version). Accepts
562
- * string paths, `file:` URL strings, or `URL` instances.
741
+ * - `files`: candidate manifest filenames in priority order
742
+ * (default `['package.json']`).
743
+ * - `inferName`: infer the CLI name from `bin` keys or `name`. Pass
744
+ * `{ scope: 'keep' }` to keep a leading `@scope/` (stripped by default).
745
+ * - `from`: anchor discovery to a file/URL/path instead of `cwd`. Pass
746
+ * `import.meta.url` for installable CLIs that must report THEIR OWN
747
+ * version. Accepts string paths, `file:` URL strings, or `URL` instances.
563
748
  *
564
749
  * @example
565
750
  * ```ts
566
- * // Auto-fill version + description from nearest package.json:
751
+ * // Deno CLI: discover OUR deno.json (then jsr.json), keep the scope in name:
567
752
  * cli('mycli')
568
- * .packageJson()
753
+ * .manifest({
754
+ * files: ['deno.json', 'jsr.json'],
755
+ * from: import.meta.url,
756
+ * inferName: { scope: 'keep' },
757
+ * })
569
758
  * .command(deploy)
570
759
  * .run();
760
+ * ```
761
+ */
762
+ manifest(settings?: ManifestSettings): CLIBuilder;
763
+ manifest(input?: PackageJsonData | ManifestSettings): CLIBuilder {
764
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
765
+ }
766
+
767
+ /**
768
+ * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
571
769
  *
572
- * // Also infer CLI name from bin key / package name:
573
- * cli('mycli')
574
- * .packageJson({ inferName: true })
575
- * .command(deploy)
576
- * .run();
770
+ * @deprecated Use {@link CLIBuilder.manifest} — `.manifest()` defaults to
771
+ * `package.json` and also supports `deno.json` / `jsr.json` via `files`.
577
772
  *
578
- * // Installable CLI; discover OUR package.json, not the consumer's:
579
- * cli('mycli')
580
- * .packageJson({ from: import.meta.url })
581
- * .command(deploy)
582
- * .run();
773
+ * @param data - Pre-loaded `package.json` metadata.
774
+ */
775
+ packageJson(data: PackageJsonData): CLIBuilder;
776
+ /**
777
+ * Discover metadata from `package.json` (preset for {@link CLIBuilder.manifest}).
778
+ *
779
+ * @deprecated Use {@link CLIBuilder.manifest}.
780
+ *
781
+ * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
782
+ */
783
+ packageJson(settings?: ManifestPresetSettings): CLIBuilder;
784
+ packageJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
785
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
786
+ }
787
+
788
+ /**
789
+ * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
790
+ * {@link CLIBuilder.manifest}).
791
+ *
792
+ * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
793
+ *
794
+ * @param data - Pre-loaded `deno.json` / `jsr.json` metadata.
795
+ */
796
+ denoJson(data: PackageJsonData): CLIBuilder;
797
+ /**
798
+ * Discover metadata from `deno.json`, `deno.jsonc`, then `jsr.json` (preset for
799
+ * {@link CLIBuilder.manifest}).
583
800
  *
584
- * // Explicit values always win:
801
+ * @deprecated Use `.manifest({ files: ['deno.json', 'deno.jsonc', 'jsr.json'] })`.
802
+ *
803
+ * @param settings - `inferName` / `from` (see {@link CLIBuilder.manifest}).
804
+ * `deno.json` / `jsr.json` have no `bin` field, so `inferName` resolves
805
+ * from `name`; pass `{ scope: 'keep' }` to retain a leading `@scope/`.
806
+ *
807
+ * @example
808
+ * ```ts
585
809
  * cli('mycli')
586
- * .packageJson()
587
- * .version('2.0.0-beta') // wins over package.json
810
+ * .denoJson({ from: import.meta.url })
811
+ * .command(deploy)
588
812
  * .run();
589
813
  * ```
590
814
  */
591
- packageJson(settings?: { readonly inferName?: boolean; readonly from?: string | URL }): CLIBuilder;
592
- packageJson(
593
- input?: PackageJsonData | { readonly inferName?: boolean; readonly from?: string | URL },
594
- ): CLIBuilder {
595
- if (isPackageJsonData(input)) {
596
- // Merge data into schema immediately so `.execute()` (which skips
597
- // runtime preflight) still picks up version/description. Explicit
598
- // `.version()`/`.description()` calls win, matching settings semantics.
599
- return new CLIBuilder({
600
- ...this.schema,
601
- ...(this.schema.version === undefined && input.version !== undefined
602
- ? { version: input.version }
603
- : {}),
604
- ...(this.schema.description === undefined && input.description !== undefined
605
- ? { description: input.description }
606
- : {}),
607
- packageJsonSettings: { inferName: false, from: undefined, data: input },
608
- });
609
- }
610
- return new CLIBuilder({
611
- ...this.schema,
612
- packageJsonSettings: {
613
- inferName: input?.inferName ?? false,
614
- from: normalizeFromSetting(input?.from),
615
- data: undefined,
616
- },
617
- });
815
+ denoJson(settings?: ManifestPresetSettings): CLIBuilder;
816
+ denoJson(input?: PackageJsonData | ManifestPresetSettings): CLIBuilder {
817
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
618
818
  }
619
819
 
620
820
  // -- Command registration ------------------------------------------------
@@ -634,7 +834,10 @@ class CLIBuilder {
634
834
  A extends Record<string, ArgBuilder<ArgConfig>>,
635
835
  C extends Record<string, unknown>,
636
836
  >(cmd: CommandBuilder<F, A, C>): CLIBuilder {
637
- assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
837
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
838
+ if (this.schema.completionsFlag !== undefined) {
839
+ assertNoCompletionsFlagCollision(cmd.schema);
840
+ }
638
841
 
639
842
  return new CLIBuilder({
640
843
  ...this.schema,
@@ -649,8 +852,11 @@ class CLIBuilder {
649
852
  * dispatch normally, but empty argv or flags-only argv falls through to
650
853
  * this command instead of showing root help.
651
854
  *
652
- * The command is also registered as a normal subcommand (can be invoked
653
- * by name). Only one default command is allowed.
855
+ * The default command is the CLI's root *surface*: its flags and arguments
856
+ * are rendered inline in root help. It is **not** a named subcommand — it
857
+ * cannot be invoked by its own name (`mycli mycmd` does not route to it) and
858
+ * it is omitted from the root `Commands:` list by default (re-enable with
859
+ * `.help({ showDefaultInCommands: true })`). Only one default is allowed.
654
860
  *
655
861
  * @example
656
862
  * ```ts
@@ -685,11 +891,13 @@ class CLIBuilder {
685
891
  }
686
892
 
687
893
  assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
894
+ if (this.schema.completionsFlag !== undefined) {
895
+ assertNoCompletionsFlagCollision(cmd.schema);
896
+ }
688
897
 
689
898
  const erased = eraseCommand(cmd);
690
899
  return new CLIBuilder({
691
900
  ...this.schema,
692
- commands: [...this.schema.commands, erased],
693
901
  defaultCommand: erased,
694
902
  });
695
903
  }
@@ -714,28 +922,36 @@ class CLIBuilder {
714
922
  // -- Built-in subcommands ------------------------------------------------
715
923
 
716
924
  /**
717
- * Register a built-in `completions` subcommand that generates shell
718
- * completion scripts.
719
- *
720
- * The generated command accepts a `--shell` flag (required, enum of
721
- * all {@link Shell} values) and writes the completion script to stdout
722
- * via `out.log()`. Unsupported shells throw a descriptive {@linkcode CLIError}
723
- * instead of a generic parse error.
724
- *
725
- * Call this **after** registering all other commands so the completion
726
- * script includes the full command set. The captured schema is a
727
- * snapshot at call time — commands registered after `.completions()`
728
- * will not appear in the generated script. Completion options are also
729
- * captured at call time.
925
+ * Register built-in shell completion.
926
+ *
927
+ * By default (`{ as: 'command' }`) this registers a `completions` subcommand
928
+ * that accepts a `shell` argument and writes the script to stdout. With
929
+ * `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
930
+ * the CLI root — no subcommand is registered, so a default command stays the
931
+ * lone root surface. The flag may be given without a value to auto-detect the
932
+ * shell from `$SHELL` / `$PSModulePath`.
933
+ *
934
+ * In subcommand mode, call this **after** registering all other commands so
935
+ * the completion script includes the full command set: that path snapshots the
936
+ * schema (and completion options) at call time, so commands registered
937
+ * afterwards will not appear in that subcommand's generated script. In flag
938
+ * mode, generation runs at execution time from the final builder schema, so
939
+ * registration order does not matter.
730
940
  *
731
941
  * @example
732
942
  * ```ts
943
+ * // Subcommand form (default):
733
944
  * cli('mycli')
734
945
  * .version('1.0.0')
735
946
  * .command(deploy)
736
- * .command(login)
737
947
  * .completions({ rootMode: 'surface' })
738
948
  * .run();
949
+ *
950
+ * // Eager-flag form, ideal for single-command CLIs:
951
+ * cli('mycli')
952
+ * .completions({ as: 'flag' })
953
+ * .default(serve)
954
+ * .run();
739
955
  * ```
740
956
  */
741
957
  completions(options?: CompletionOptions): CLIBuilder {
@@ -746,17 +962,32 @@ class CLIBuilder {
746
962
  });
747
963
  }
748
964
 
965
+ // `as: 'flag'` exposes an eager `--completions <shell>` flag instead of a
966
+ // subcommand. The planner intercepts it before dispatch (see planner.ts)
967
+ // and root help advertises it in the Flags section. No subcommand is
968
+ // registered, so the default command stays the lone root surface.
969
+ if (options?.as === 'flag') {
970
+ // The planner intercepts `--completions` before dispatch, so no command
971
+ // may already reserve that flag name.
972
+ if (this.schema.defaultCommand !== undefined) {
973
+ assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
974
+ }
975
+ for (const registered of this.schema.commands) {
976
+ assertNoCompletionsFlagCollision(registered.schema);
977
+ }
978
+ return new CLIBuilder({
979
+ ...this.schema,
980
+ hasBuiltInCompletions: true,
981
+ completionsFlag: { shells: SHELLS, options },
982
+ });
983
+ }
984
+
749
985
  // Capture current schema — includes all commands registered so far.
750
986
  // The completions command itself is deliberately excluded from the
751
987
  // generated script (it would be noise in shell completions).
752
988
  const cliSchema = this.schema;
753
989
  const completionOptions = options;
754
990
 
755
- // Supported shells for validation. Keep in sync with completion/index.ts SHELLS.
756
- const shellMap = new Map<string, Shell>();
757
- for (const s of SHELLS) shellMap.set(s, s);
758
- shellMap.set('pwsh', 'powershell');
759
-
760
991
  const cmd = command('completions')
761
992
  .alias('completion')
762
993
  .description('Generate shell completion script')
@@ -766,12 +997,9 @@ class CLIBuilder {
766
997
  .custom((raw: string): Shell => {
767
998
  // Normalize $SHELL paths across Unix/Windows:
768
999
  // /bin/zsh → zsh, C:\Program Files\PowerShell\7\pwsh.exe → pwsh
769
- const segments = raw.split(/[\\/]/);
770
- const basename = segments[segments.length - 1] ?? raw;
771
- const name = basename.replace(/\.(?:exe|cmd|bat)$/i, '');
772
- const shell = shellMap.get(name);
1000
+ const shell = normalizeShell(raw);
773
1001
  if (shell === undefined) {
774
- throw new Error(`Unknown shell '${name}'. Valid shells: ${SHELLS.join(', ')}`);
1002
+ throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(', ')}`);
775
1003
  }
776
1004
  return shell;
777
1005
  })
@@ -833,12 +1061,14 @@ class CLIBuilder {
833
1061
  }
834
1062
  clearRequestedExitCode(out);
835
1063
 
836
- // Resolve help options — default binName to CLI program name,
837
- // hyperlinks to TTY detection (escapes never leak into piped output)
1064
+ // Resolve help options — builder-level `.help()` config under runtime
1065
+ // `options.help` (runtime wins), then default binName to the CLI program
1066
+ // name and hyperlinks to TTY detection (escapes never leak into piped output).
838
1067
  const helpOptions: HelpOptions = {
1068
+ ...this.schema.helpConfig,
839
1069
  ...options?.help,
840
1070
  binName: options?.help?.binName ?? this.schema.name,
841
- hyperlinks: options?.help?.hyperlinks ?? out.isTTY,
1071
+ hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isTTY,
842
1072
  };
843
1073
 
844
1074
  // -- Shared options for command execution ----------------------------------
@@ -864,6 +1094,34 @@ class CLIBuilder {
864
1094
  out.log(planned.version);
865
1095
  return buildRunResult({ exitCode: 0, error: undefined }, captured);
866
1096
 
1097
+ case 'root-completions': {
1098
+ const shell = planned.shell ?? detectShell(options?.env ?? {});
1099
+ if (shell === undefined) {
1100
+ const error = new CLIError('Could not detect shell', {
1101
+ code: 'MISSING_VALUE',
1102
+ suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`,
1103
+ });
1104
+ if (jsonMode) {
1105
+ out.json({ error: error.toJSON() });
1106
+ } else {
1107
+ out.error(error.message);
1108
+ out.error(`Suggestion: ${error.suggest}`);
1109
+ }
1110
+ return buildRunResult({ exitCode: error.exitCode, error }, captured);
1111
+ }
1112
+ const completionSchema =
1113
+ helpOptions.binName === undefined || helpOptions.binName === this.schema.name
1114
+ ? this.schema
1115
+ : { ...this.schema, name: helpOptions.binName };
1116
+ const script = generateCompletion(completionSchema, shell, planned.options);
1117
+ if (jsonMode) {
1118
+ out.json({ shell, script });
1119
+ } else {
1120
+ out.log(script);
1121
+ }
1122
+ return buildRunResult({ exitCode: 0, error: undefined }, captured);
1123
+ }
1124
+
867
1125
  case 'root-help': {
868
1126
  const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
869
1127
  out.log(helpText);
@@ -1069,10 +1327,124 @@ function resolveHelpLinksSchema(schema: CLISchema): CLISchema {
1069
1327
  };
1070
1328
  }
1071
1329
 
1330
+ // --- manifest discovery settings
1331
+
1332
+ /** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
1333
+ const DEFAULT_MANIFEST_FILES: readonly string[] = ['package.json'];
1334
+
1335
+ /** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
1336
+ const DENO_MANIFEST_FILES: readonly string[] = ['deno.json', 'deno.jsonc', 'jsr.json'];
1337
+
1338
+ /**
1339
+ * CLI-name inference control for {@link ManifestSettings.inferName}.
1340
+ *
1341
+ * - `false` (or omitted): do not infer the name.
1342
+ * - `true`: infer, stripping a leading `@scope/` from the `name` fallback.
1343
+ * - `{ scope: 'keep' }`: infer, keeping the full scoped name.
1344
+ * - `{ scope: 'strip' }`: infer, stripping the scope (explicit form of `true`).
1345
+ *
1346
+ * `scope` is required in the object form: an empty `{}` is rejected so that an
1347
+ * options object can never silently enable inference (use `true` for that).
1348
+ */
1349
+ type InferNameOption = boolean | { readonly scope: 'keep' | 'strip' };
1350
+
1351
+ /** Discovery settings accepted by {@link CLIBuilder.manifest}. */
1352
+ interface ManifestSettings {
1353
+ /** Infer the CLI name from `bin` keys or `name`. @defaultValue `false` */
1354
+ readonly inferName?: InferNameOption;
1355
+ /** Anchor discovery to a file/URL/path instead of `cwd`. */
1356
+ readonly from?: string | URL;
1357
+ /**
1358
+ * Candidate manifest filenames in priority order — NOT npm's `files` publish
1359
+ * globs. Discovery probes each name per directory and takes the first that
1360
+ * parses.
1361
+ *
1362
+ * @defaultValue `['package.json']`
1363
+ */
1364
+ readonly files?: readonly string[];
1365
+ }
1366
+
1367
+ /**
1368
+ * Discovery settings for the `.packageJson()` / `.denoJson()` presets (no `files`).
1369
+ *
1370
+ * @deprecated Both presets are deprecated; use {@link ManifestSettings} with
1371
+ * {@link CLIBuilder.manifest}.
1372
+ */
1373
+ type ManifestPresetSettings = Omit<ManifestSettings, 'files'>;
1374
+
1375
+ /**
1376
+ * Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
1377
+ * pair stored in {@link ResolvedManifestSettings}.
1378
+ *
1379
+ * @internal
1380
+ */
1381
+ function normalizeInferName(option: InferNameOption | undefined): {
1382
+ readonly inferName: boolean;
1383
+ readonly stripScope: boolean;
1384
+ } {
1385
+ if (option === undefined || option === false) return { inferName: false, stripScope: true };
1386
+ if (option === true) return { inferName: true, stripScope: true };
1387
+ return { inferName: true, stripScope: option.scope !== 'keep' };
1388
+ }
1389
+
1390
+ /**
1391
+ * Build the next {@link CLISchema} for a manifest builder method.
1392
+ *
1393
+ * Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
1394
+ * {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
1395
+ * merges `version`/`description` immediately so `.execute()` sees them; the
1396
+ * settings overload stores discovery config for runtime preflight.
1397
+ *
1398
+ * @internal
1399
+ */
1400
+ function buildManifestSchema(
1401
+ schema: CLISchema,
1402
+ input: PackageJsonData | ManifestSettings | undefined,
1403
+ defaultFiles: readonly string[],
1404
+ pinFiles: boolean,
1405
+ ): CLISchema {
1406
+ if (isPackageJsonData(input)) {
1407
+ // Merge data into schema immediately so `.execute()` (which skips runtime
1408
+ // preflight) still picks up version/description. Explicit
1409
+ // `.version()`/`.description()` calls win, matching settings semantics.
1410
+ return {
1411
+ ...schema,
1412
+ ...(schema.version === undefined && input.version !== undefined
1413
+ ? { version: input.version }
1414
+ : {}),
1415
+ ...(schema.description === undefined && input.description !== undefined
1416
+ ? { description: input.description }
1417
+ : {}),
1418
+ packageJsonSettings: {
1419
+ inferName: false,
1420
+ stripScope: true,
1421
+ from: undefined,
1422
+ files: defaultFiles,
1423
+ data: input,
1424
+ },
1425
+ };
1426
+ }
1427
+ const { inferName, stripScope } = normalizeInferName(input?.inferName);
1428
+ // Presets (`pinFiles`) always use their fixed list: the `Omit<…,'files'>` guard
1429
+ // only stops fresh literals at compile time, so a `ManifestSettings`-typed
1430
+ // variable could otherwise leak `files` through the data-overload dispatch gap.
1431
+ const files = pinFiles ? defaultFiles : (input?.files ?? defaultFiles);
1432
+ return {
1433
+ ...schema,
1434
+ packageJsonSettings: {
1435
+ inferName,
1436
+ stripScope,
1437
+ from: normalizeFromSetting(input?.from),
1438
+ files,
1439
+ data: undefined,
1440
+ },
1441
+ };
1442
+ }
1443
+
1072
1444
  // --- packageJson.from normalisation
1073
1445
 
1074
1446
  /**
1075
- * Coerce a {@link PackageJsonSettings.from | `packageJson.from`} input
1447
+ * Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
1076
1448
  * (string path, `file:` URL string, or {@link URL} instance) to a plain
1077
1449
  * filesystem path string. `undefined` passes through unchanged.
1078
1450
  *
@@ -1114,6 +1486,19 @@ function normalizeFromSetting(from: string | URL | undefined): string | undefine
1114
1486
  * `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
1115
1487
  * object (`inferName` / `from`) falls through to the settings overload.
1116
1488
  *
1489
+ * npm's `files` field (publish globs) is intentionally NOT recognised here, so
1490
+ * an object whose only key is `files` routes to the settings overload — where
1491
+ * `files` means candidate manifest filenames, never publish globs. Manifests
1492
+ * that publish a CLI carry `name`/`version`, so those route to the data overload
1493
+ * as expected.
1494
+ *
1495
+ * Edge case: a metadata-less manifest (e.g. a versionless private-root
1496
+ * `package.json` carrying only `files`/`private`) routes to settings, so its
1497
+ * `files` would be read as candidate filenames and the object is not stored as
1498
+ * data. This is harmless in practice — a metadata-less manifest contributes no
1499
+ * `version`/`description` either way — but it means a pre-loaded object must
1500
+ * carry real metadata to be honoured as data.
1501
+ *
1117
1502
  * @internal
1118
1503
  */
1119
1504
  function isPackageJsonData(value: unknown): value is PackageJsonData {
@@ -1197,6 +1582,8 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1197
1582
  packageJsonSettings: undefined,
1198
1583
  helpLinks: undefined,
1199
1584
  hasBuiltInCompletions: false,
1585
+ completionsFlag: undefined,
1586
+ helpConfig: undefined,
1200
1587
  plugins: [],
1201
1588
  });
1202
1589
  }
@@ -1211,5 +1598,17 @@ export type {
1211
1598
  PluginCommandContext,
1212
1599
  ResolvedCommandParams,
1213
1600
  } from './plugin.ts';
1214
- export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
1601
+ export type {
1602
+ CLIOptions,
1603
+ CLIRunOptions,
1604
+ CLISchema,
1605
+ CompletionsFlagConfig,
1606
+ ConfigSettings,
1607
+ HelpConfig,
1608
+ InferNameOption,
1609
+ ManifestPresetSettings,
1610
+ ManifestSettings,
1611
+ PackageJsonSettings,
1612
+ ResolvedManifestSettings,
1613
+ };
1215
1614
  export { CLIBuilder, cli, formatRootHelp, plugin };