@kjanat/dreamcli 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/dist/core/cli/dispatch.d.mts +30 -2
  3. package/dist/core/cli/dispatch.mjs +1 -1
  4. package/dist/core/cli/help-links.d.mts +28 -0
  5. package/dist/core/cli/help-links.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +53 -2
  7. package/dist/core/cli/index.mjs +1 -1
  8. package/dist/core/cli/planner.mjs +1 -1
  9. package/dist/core/cli/root-help.d.mts +4 -0
  10. package/dist/core/cli/root-help.mjs +4 -5
  11. package/dist/core/cli/runtime-preflight.d.mts +3 -0
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/config/index.d.mts +2 -2
  14. package/dist/core/config/package-json.d.mts +36 -1
  15. package/dist/core/config/package-json.mjs +1 -1
  16. package/dist/core/execution/index.mjs +1 -1
  17. package/dist/core/help/ansi.d.mts +78 -0
  18. package/dist/core/help/ansi.mjs +2 -0
  19. package/dist/core/help/index.d.mts +9 -1
  20. package/dist/core/help/index.mjs +4 -5
  21. package/dist/core/parse/index.d.mts +31 -1
  22. package/dist/core/parse/index.mjs +1 -1
  23. package/dist/index.d.mts +4 -2
  24. package/dist/index.mjs +1 -1
  25. package/dist/version.mjs +1 -1
  26. package/package.json +5 -2
  27. package/src/core/cli/dispatch.ts +70 -7
  28. package/src/core/cli/help-links.ts +82 -0
  29. package/src/core/cli/index.ts +104 -6
  30. package/src/core/cli/planner.ts +23 -5
  31. package/src/core/cli/root-help.ts +36 -53
  32. package/src/core/cli/runtime-preflight.ts +5 -0
  33. package/src/core/config/index.ts +2 -2
  34. package/src/core/config/package-json.ts +119 -2
  35. package/src/core/execution/index.ts +1 -9
  36. package/src/core/help/ansi.ts +144 -0
  37. package/src/core/help/index.ts +9 -50
  38. package/src/core/parse/index.ts +21 -1
  39. package/src/index.ts +4 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,46 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.3.0] - 2026-06-20
11
+
12
+ ### Fixed
13
+
14
+ - **Command dispatch now respects flag value-arity** — a space-separated value-flag value (e.g.
15
+ `--source anthropic`) is no longer mistaken for a command name when it collides with a registered
16
+ command, so the default-command fallback runs as intended
17
+ (https://github.com/kjanat/dreamcli/issues/25). The command-name scan now skips the token a
18
+ space-separated value-flag consumes (mirroring the parser's own value-consumption rules); the
19
+ inline `--source=anthropic` form already worked, and both forms are now consistent.
20
+ - **Root `--version`/`--json` interception now respects the `--` end-of-options separator**
21
+ (https://github.com/kjanat/dreamcli/issues/28). A `--version` or `--json` token after `--` is
22
+ treated as a literal positional instead of triggering version output or JSON mode.
23
+
24
+ ## [2.2.1] - 2026-06-10
25
+
26
+ ### Added
27
+
28
+ - **`.links()` — OSC 8 hyperlinks in the root-help header** — the program name and version on the
29
+ first line of root `--help` output can now carry
30
+ [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) in
31
+ supporting terminals ([#20](https://github.com/kjanat/dreamcli/issues/20)). Pass explicit URLs
32
+ (`.links({ name, version })`) or call `.links()` with no arguments to derive them from
33
+ `package.json` metadata when `.packageJson()` is active: the name links to the normalized
34
+ `repository` URL (falling back to `homepage`), and the version links to the forge release tag
35
+ (`{repo}/releases/tag/v{version}` on GitHub, `{repo}/-/releases/v{version}` on GitLab). Escapes
36
+ are emitted only when stdout is a TTY (overridable via the new `help.hyperlinks` option) and only
37
+ on the header line — usage lines, the `--help` hint, the commands table, `--version` output, and
38
+ completion scripts stay plain.
39
+ - **ANSI/OSC-aware help width helpers** — help padding and wrapping now measure _visible_ width:
40
+ the shared `padEnd()`/`wrapText()` helpers strip ANSI CSI (colors) and OSC (hyperlink) escape
41
+ sequences before counting columns, so escape-bearing text no longer mangles `--help` alignment.
42
+ New public exports `osc8(url, text)` (wrap text in an OSC 8 hyperlink) and `visibleWidth(text)`
43
+ (escape-aware width measurement) support custom help rendering.
44
+ - **`packageRepositoryUrl(pkg)`** — new public helper that normalizes a package's `repository`
45
+ field to a browsable `https://` URL, handling the locator formats npm accepts (`{ type, url }`
46
+ object form, `git+`/`.git` affixes, scp-style `git@host:u/r.git`, and the
47
+ `github:`/`gitlab:`/`bitbucket:`/bare `u/r` shorthands). `PackageJsonData` now also parses the
48
+ `homepage` and `repository` fields.
49
+
10
50
  ## [2.2.0] - 2026-06-09
11
51
 
12
52
  ### Added
@@ -764,7 +804,9 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
764
804
  - MIT License.
765
805
  - Markdownlint configuration.
766
806
 
767
- [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.2.0...HEAD
807
+ [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.3.0...HEAD
808
+ [2.3.0]: https://github.com/kjanat/dreamcli/compare/v2.2.1...v2.3.0
809
+ [2.2.1]: https://github.com/kjanat/dreamcli/compare/v2.2.0...v2.2.1
768
810
  [2.2.0]: https://github.com/kjanat/dreamcli/compare/v2.1.0...v2.2.0
769
811
  [2.1.0]: https://github.com/kjanat/dreamcli/compare/v2.0.1...v2.1.0
770
812
  [2.0.1]: https://github.com/kjanat/dreamcli/compare/v2.0.0...v2.0.1
@@ -1,6 +1,15 @@
1
+ import { FlagSchema } from "../schema/flag.mjs";
1
2
  import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
2
3
 
3
4
  //#region src/core/cli/dispatch.d.ts
5
+ /**
6
+ * Flag lookup (name/alias → `[canonicalName, schema]`) used to make the
7
+ * command-name scan aware of value-flag arity. Built from the flags valid at
8
+ * the current dispatch level via {@link buildFlagLookup}.
9
+ *
10
+ * @internal
11
+ */
12
+ type ValueFlagLookup = ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
4
13
  /** Successful dispatch — target command found with argv path. */
5
14
  interface DispatchMatch {
6
15
  /** Discriminant — a command name in argv matched a registered command. */
@@ -53,11 +62,30 @@ type DispatchResult = DispatchMatch | DispatchNeedsSubcommand | DispatchUnknown;
53
62
  * @param argv - Remaining argv tokens (command names + flags + args).
54
63
  * @param commands - Command map at the current tree level.
55
64
  * @param ancestorPath - Schema path from root to current level (exclusive).
65
+ * @param valueFlags - Lookup of flags valid at this level, used so a
66
+ * space-separated value-flag's value (`--region eu`) is not mistaken for a
67
+ * command name. Empty by default (arity-unaware, legacy behaviour).
56
68
  * @returns Discriminated dispatch result.
57
69
  *
58
70
  * @internal
59
71
  */
60
- declare function dispatch(argv: readonly string[], commands: ReadonlyMap<string, ErasedCommand>, ancestorPath?: readonly CommandSchema[]): DispatchResult;
72
+ declare function dispatch(argv: readonly string[], commands: ReadonlyMap<string, ErasedCommand>, ancestorPath?: readonly CommandSchema[], valueFlags?: ValueFlagLookup): DispatchResult;
73
+ /**
74
+ * Whether a flag token consumes the following argv token as its value.
75
+ *
76
+ * Mirrors the parser's value-consumption rules (`parseLongFlag` /
77
+ * `parseShortFlags`) so the command-name scan skips exactly the tokens the
78
+ * parser would treat as flag values:
79
+ * - `--flag value` → consumes when `--flag` is a known value-flag.
80
+ * - `--flag=value` → self-contained, consumes nothing.
81
+ * - `-abc value` → consumes only when the trailing short flag is a value-flag;
82
+ * an earlier value-flag char takes the rest of the group as an inline value.
83
+ *
84
+ * Unknown flags conservatively consume nothing (the parser reports them later).
85
+ *
86
+ * @internal
87
+ */
88
+ declare function consumesFollowingToken(token: string, valueFlags: ValueFlagLookup): boolean;
61
89
  /**
62
90
  * Levenshtein distance between two strings.
63
91
  * @internal
@@ -82,4 +110,4 @@ declare function findClosestCommand(input: string, commands: readonly ErasedComm
82
110
  */
83
111
  declare function uniqueCommands(commands: ReadonlyMap<string, ErasedCommand>): readonly ErasedCommand[];
84
112
  //#endregion
85
- export { type DispatchMatch, type DispatchNeedsSubcommand, type DispatchResult, type DispatchUnknown, dispatch, findClosestCommand, levenshtein, uniqueCommands };
113
+ export { type DispatchMatch, type DispatchNeedsSubcommand, type DispatchResult, type DispatchUnknown, type ValueFlagLookup, consumesFollowingToken, dispatch, findClosestCommand, levenshtein, uniqueCommands };
@@ -1 +1 @@
1
- function e(t,n,i=[]){let a=-1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){e+1<t.length&&(a=e+1);break}if(n!==void 0&&!n.startsWith(`-`)){a=e;break}}if(a===-1)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let o=t[a];if(o===void 0)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let s=n.get(o);if(s===void 0)return{kind:`unknown`,input:o,candidates:r(n),parentPath:i};let c=[...t.slice(0,a),...t.slice(a+1)],l=[...i,s.schema];if(s.subcommands.size>0){let t=e(c,s.subcommands,l);switch(t.kind){case`match`:return t;case`unknown`:return t.input===``?s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:{kind:`needs-subcommand`,command:s,commandPath:l}:s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:t;case`needs-subcommand`:return t;default:return t}}return{kind:`match`,command:s,commandPath:l,remainingArgv:c}}function t(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint16Array(i),o=new Uint16Array(i);for(let e=0;e<=r;e++)a[e]=e;for(let i=1;i<=n;i++){o[0]=i;for(let n=1;n<=r;n++){let r=e.charAt(i-1)===t.charAt(n-1)?0:1,s=a[n]??0,c=o[n-1]??0,l=a[n-1]??0;o[n]=Math.min(s+1,c+1,l+r)}[a,o]=[o,a]}return a[r]??Math.max(n,r)}function n(e,n){let r,i=4;for(let a of n){let n=t(e,a.schema.name);n<i&&(i=n,r=a.schema.name);for(let n of a.schema.aliases){let o=t(e,n);o<i&&(i=o,r=a.schema.name)}}return i<=3?r:void 0}function r(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}export{e as dispatch,n as findClosestCommand};
1
+ import{buildFlagLookup as e,flagExpectsValue as t}from"../parse/index.mjs";function n(t,i,a=[],s=new Map){let c=-1;for(let e=0;e<t.length;e++){let n=t[e];if(n!==void 0){if(n===`--`){e+1<t.length&&(c=e+1);break}if(n.startsWith(`-`)){r(n,s)&&e++;continue}c=e;break}}if(c===-1)return{kind:`unknown`,input:``,candidates:o(i),parentPath:a};let l=t[c];if(l===void 0)return{kind:`unknown`,input:``,candidates:o(i),parentPath:a};let u=i.get(l);if(u===void 0)return{kind:`unknown`,input:l,candidates:o(i),parentPath:a};let d=[...t.slice(0,c),...t.slice(c+1)],f=[...a,u.schema];if(u.subcommands.size>0){let t=n(d,u.subcommands,f,e(u.schema.flags));switch(t.kind){case`match`:return t;case`unknown`:return t.input===``?u.schema.hasAction?{kind:`match`,command:u,commandPath:f,remainingArgv:d}:{kind:`needs-subcommand`,command:u,commandPath:f}:u.schema.hasAction?{kind:`match`,command:u,commandPath:f,remainingArgv:d}:t;case`needs-subcommand`:return t;default:return t}}return{kind:`match`,command:u,commandPath:f,remainingArgv:d}}function r(e,n){if(e.startsWith(`--`)){if(e.includes(`=`))return!1;let r=n.get(e.slice(2));return r!==void 0&&t(r[1])}let r=e.slice(1);for(let e=0;e<r.length;e++){let i=n.get(r.charAt(e));if(i===void 0)return!1;if(t(i[1]))return e===r.length-1}return!1}function i(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint16Array(i),o=new Uint16Array(i);for(let e=0;e<=r;e++)a[e]=e;for(let i=1;i<=n;i++){o[0]=i;for(let n=1;n<=r;n++){let r=e.charAt(i-1)===t.charAt(n-1)?0:1,s=a[n]??0,c=o[n-1]??0,l=a[n-1]??0;o[n]=Math.min(s+1,c+1,l+r)}[a,o]=[o,a]}return a[r]??Math.max(n,r)}function a(e,t){let n,r=4;for(let a of t){let t=i(e,a.schema.name);t<r&&(r=t,n=a.schema.name);for(let t of a.schema.aliases){let o=i(e,t);o<r&&(r=o,n=a.schema.name)}}return r<=3?n:void 0}function o(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}export{n as dispatch,a as findClosestCommand};
@@ -0,0 +1,28 @@
1
+ import { PackageJsonData } from "../config/package-json.mjs";
2
+
3
+ //#region src/core/cli/help-links.d.ts
4
+ /**
5
+ * OSC 8 hyperlink targets for the root-help header.
6
+ *
7
+ * Set via `CLIBuilder.links()`; fields left `undefined` are derived from
8
+ * package.json metadata when `.packageJson()` is active.
9
+ */
10
+ interface HelpLinks {
11
+ /** URL the program name links to (e.g. the repository or homepage). */
12
+ readonly name: string | undefined;
13
+ /** URL the version links to (e.g. the release tag). */
14
+ readonly version: string | undefined;
15
+ }
16
+ /**
17
+ * Fill `undefined` link fields from package.json metadata.
18
+ *
19
+ * Explicit URLs always win. The name falls back to the normalized
20
+ * `repository` URL, then `homepage`; the version falls back to the forge
21
+ * release-tag URL when both a repository and a version are known.
22
+ * Idempotent — already-resolved fields pass through unchanged.
23
+ *
24
+ * @internal
25
+ */
26
+ declare function deriveHelpLinks(links: HelpLinks | undefined, pkg: PackageJsonData | undefined, version: string | undefined): HelpLinks | undefined;
27
+ //#endregion
28
+ export { type HelpLinks, deriveHelpLinks };
@@ -0,0 +1 @@
1
+ import{packageRepositoryUrl as e}from"../config/package-json.mjs";function t(e,t){let n;try{n=new URL(e).hostname}catch{return}if(n===`github.com`)return`${e}/releases/tag/v${t}`;if(n===`gitlab.com`)return`${e}/-/releases/v${t}`}function n(n,r,i){if(n===void 0)return;if(r===void 0||n.name!==void 0&&n.version!==void 0)return n;let a=e(r);return{name:n.name??a??r.homepage,version:n.version??(a!==void 0&&i!==void 0?t(a,i):void 0)}}export{n as deriveHelpLinks};
@@ -3,9 +3,10 @@ import { FlagBuilder, FlagConfig } from "../schema/flag.mjs";
3
3
  import { BeforeParseParams, CLIPlugin, CLIPluginHooks, PluginCommandContext, ResolvedCommandParams, plugin } from "./plugin.mjs";
4
4
  import { RunOptions, RunResult } from "../schema/run.mjs";
5
5
  import { CommandBuilder, ErasedCommand } from "../schema/command.mjs";
6
- import { CompletionOptions } from "../completion/shells/shared.mjs";
7
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
8
7
  import { PackageJsonData } from "../config/package-json.mjs";
8
+ import { HelpLinks } from "./help-links.mjs";
9
+ import { CompletionOptions } from "../completion/shells/shared.mjs";
9
10
  import { FormatLoader } from "../config/index.mjs";
10
11
  import { formatRootHelp } from "./root-help.mjs";
11
12
 
@@ -56,6 +57,14 @@ interface CLISchema {
56
57
  * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
57
58
  */
58
59
  readonly packageJsonSettings: PackageJsonSettings | undefined;
60
+ /**
61
+ * OSC 8 hyperlink targets for the root-help header (name/version).
62
+ *
63
+ * Set via the {@linkcode CLIBuilder.links | .links()} builder method.
64
+ * Fields left `undefined` are derived from package.json metadata
65
+ * (`repository` / `homepage`) when `.packageJson()` is active.
66
+ */
67
+ readonly helpLinks: HelpLinks | undefined;
59
68
  /** Whether built-in `.completions()` command registration is active. */
60
69
  readonly hasBuiltInCompletions: boolean;
61
70
  /** Registered CLI plugins. */
@@ -179,6 +188,48 @@ declare class CLIBuilder {
179
188
  * @returns The builder (for chaining).
180
189
  */
181
190
  description(text: string): CLIBuilder;
191
+ /**
192
+ * Make the root-help header clickable with OSC 8 hyperlinks.
193
+ *
194
+ * Links the program name and version on the first line of root `--help`
195
+ * output in terminals that support
196
+ * [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
197
+ * The escapes are only emitted when stdout is a TTY (overridable via
198
+ * `options.help.hyperlinks`), and only in the header — usage lines, the
199
+ * `--help` hint, the commands table, and completion scripts stay plain.
200
+ *
201
+ * URLs not provided here are derived from package.json metadata when
202
+ * `.packageJson()` is active (works with both filesystem discovery and
203
+ * pre-loaded data):
204
+ * - **name** → normalized `repository` URL, falling back to `homepage`
205
+ * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
206
+ * GitHub, `{repo}/-/releases/v{version}` on GitLab)
207
+ *
208
+ * @param links - Explicit URLs; omit to derive everything from package.json.
209
+ * @returns The builder (for chaining).
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * // Derive both links from package.json repository/homepage:
214
+ * cli('mycli')
215
+ * .packageJson()
216
+ * .links()
217
+ * .run();
218
+ *
219
+ * // Explicit URLs (no package.json required):
220
+ * cli('mycli')
221
+ * .version('1.0.0')
222
+ * .links({
223
+ * name: 'https://github.com/me/mycli',
224
+ * version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
225
+ * })
226
+ * .run();
227
+ * ```
228
+ */
229
+ links(links?: {
230
+ readonly name?: string | URL;
231
+ readonly version?: string | URL;
232
+ }): CLIBuilder;
182
233
  /**
183
234
  * Enable automatic config file discovery.
184
235
  *
@@ -477,4 +528,4 @@ declare function cli(name: string): CLIBuilder;
477
528
  /** Create a new CLI program builder from an options object. */
478
529
  declare function cli(options: CLIOptions): CLIBuilder;
479
530
  //#endregion
480
- export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
531
+ export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type HelpLinks, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{planInvocation as f}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as p}from"./root-help.mjs";import{prepareRuntimePreflight as m}from"./runtime-preflight.mjs";function h(e){return[e.name,...e.aliases]}function g(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function _(t,n){let r=new Map;for(let e of t)for(let t of h(e.schema))g(`root`,r,t,e.schema.name);for(let t of h(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function v(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=h(r.schema);for(let t of i)g(e.schema.name,n,t,r.schema.name);let a=v(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function y(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var b=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return E(e)?new u({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:T(e?.from),data:void 0}})}command(e){return _(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,v(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});_(this.schema.commands,t.schema);let n=v(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=f({schema:this.schema,argv:e,help:u,output:m});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=p(this.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=y(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?w(t.argv):void 0,r=await m({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const x=new Set([`bun`,`deno`,`node`,`tsx`]);function S(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function C(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return x.has(t)}function w(e){let t=e[0],n=e[1],r=t===void 0?void 0:S(t);if(r!==void 0&&C(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:S(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:S(n)}return t===void 0?void 0:S(t)}function T(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function E(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e}function D(e){return new b({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{b as CLIBuilder,D as cli};
1
+ import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{includesBeforeSeparator as i}from"../parse/index.mjs";import{buildRunResult as a,executeCommand as o}from"../execution/index.mjs";import{createCaptureOutput as s,createOutput as c}from"../output/index.mjs";import{arg as l}from"../schema/arg.mjs";import{command as u}from"../schema/command.mjs";import{runCommand as d}from"../testkit/index.mjs";import{createAdapter as f}from"../../runtime/auto.mjs";import{deriveHelpLinks as p}from"./help-links.mjs";import{planInvocation as m}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as h}from"./root-help.mjs";import{prepareRuntimePreflight as g}from"./runtime-preflight.mjs";function _(e){return[e.name,...e.aliases]}function v(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function y(t,n){let r=new Map;for(let e of t)for(let t of _(e.schema))v(`root`,r,t,e.schema.name);for(let t of _(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function b(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=_(r.schema);for(let t of i)v(e.schema.name,n,t,r.schema.name);let a=b(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return d(e,t,n)}}}function x(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var S=class d{schema;constructor(e){this.schema=e}version(e){return new d({...this.schema,version:e})}description(e){return new d({...this.schema,description:e})}links(e){return new d({...this.schema,helpLinks:{name:D(e?.name),version:D(e?.version)}})}config(e,t){return new d({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new d({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return A(e)?new d({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new d({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:k(e?.from),data:void 0}})}command(e){return y(this.schema.commands,e.schema),new d({...this.schema,commands:[...this.schema.commands,b(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});y(this.schema.commands,t.schema);let n=b(t);return new d({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new d({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=u(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,l.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new d({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=i(e,`--json`)||t?.jsonMode===!0,c={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},l,u;t?.out===void 0?[l,u]=s(Object.keys(c).length>0?c:void 0):(l=t.out,u=t.captured??{stdout:[],stderr:[],activity:[]});let d={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??l.isTTY},f={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},p={jsonMode:n,isTTY:l.isTTY,verbosity:t?.verbosity??`normal`},g=m({schema:this.schema,argv:e,help:d,output:p});switch(g.kind){case`root-version`:return l.log(g.version),a({exitCode:0,error:void 0},u);case`root-help`:{let e=h(O(this.schema),g.help);return l.log(e),a({exitCode:0,error:void 0},u)}case`dispatch-error`:return n?l.json({error:g.error.toJSON()}):(l.error(g.error.message),g.error.suggest!==void 0&&g.error.code!==`NO_ACTION`&&l.error(`Suggestion: ${g.error.suggest}`)),a({exitCode:g.error.exitCode,error:g.error},u);case`needs-subcommand`:{let e=r(g.command.schema,g.help);return l.log(e),a({exitCode:0,error:void 0},u)}case`match`:{let e=x(f,g.plan.help??d,g.plan.meta);return g.plan.command._command===void 0?g.plan.command._execute(g.plan.argv,{...e,mergedSchema:g.plan.mergedSchema}):a(await o({command:g.plan.command._command,argv:g.plan.argv,out:l,schema:g.plan.mergedSchema,meta:g.plan.meta,options:e}),u)}}}async run(e){let t=e?.adapter??f(),n=this.schema.inheritName?E(t.argv):void 0,r=await g({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new d(r.schema),a={...e,...r.inputs,out:c({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const C=new Set([`bun`,`deno`,`node`,`tsx`]);function w(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function T(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return C.has(t)}function E(e){let t=e[0],n=e[1],r=t===void 0?void 0:w(t);if(r!==void 0&&T(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:w(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:w(n)}return t===void 0?void 0:w(t)}function D(e){if(e!==void 0)return e instanceof URL?e.href:e}function O(e){return e.helpLinks===void 0?e:{...e,helpLinks:p(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function k(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function A(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e||`homepage`in e||`repository`in e}function j(e){return new S({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,helpLinks:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{S as CLIBuilder,j as cli};
@@ -1 +1 @@
1
- import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{dispatch as r,findClosestCommand as i}from"./dispatch.mjs";function a(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function o(e){let n=new Map,r=(e,r)=>{let i=n.get(e);if(i!==void 0)throw new t(`Duplicate root command route '${e}' (${i.schema.name} and ${r.schema.name})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure root command names and aliases are unique`});n.set(e,r)};for(let t of e){r(t.schema.name,t);for(let e of t.schema.aliases)r(e,t)}return n}function s(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function c(e){return{command:e.command,mergedSchema:s(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function l(e,t,n,r,i,o){return{kind:`match`,plan:c({command:t,commandPath:n,argv:r,meta:a(e,i,t.schema.name),plugins:e.plugins,output:o,help:i})}}function u(e){let a=e.argv.includes(`--json`)?e.argv.filter(e=>e!==`--json`):e.argv;if(e.schema.version!==void 0&&(a.includes(`--version`)||a.includes(`-V`)))return{kind:`root-version`,version:e.schema.version};let s=a[0];if(s===`--help`||s===`-h`)return{kind:`root-help`,help:e.help};if(s===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=a.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:u({...e,argv:[...t,`--help`]})}if(s===void 0&&e.schema.defaultCommand===void 0)return{kind:`root-help`,help:e.help};if(e.schema.commands.length===0)return{kind:`dispatch-error`,error:new t(`No commands registered`,{code:`NO_ACTION`,suggest:`Add commands via .command() before calling .run()`})};let c=r(a,o(e.schema.commands)),d=e.schema.defaultCommand;switch(c.kind){case`unknown`:{if(d!==void 0&&c.parentPath.length===0&&(c.input===``?void 0:i(c.input,c.candidates))===void 0)return l(e.schema,d,[d.schema],a,e.help,e.output);if(c.input===``){let t=a.find(e=>e.startsWith(`-`));return t===void 0?{kind:`root-help`,help:e.help}:{kind:`dispatch-error`,error:new n(`Unknown flag ${t}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${e.schema.name} --help' for available commands`})}}let t=i(c.input,c.candidates),r=c.parentPath.length>0?`${e.schema.name} ${c.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${c.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=c.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:c.command,commandPath:c.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return l(e.schema,c.command,c.commandPath,c.remainingArgv,e.help,e.output)}}export{u as planInvocation};
1
+ import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{buildFlagLookup as r,includesBeforeSeparator as i}from"../parse/index.mjs";import{dispatch as a,findClosestCommand as o}from"./dispatch.mjs";function s(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function c(e){let n=new Map,r=(e,r)=>{let i=n.get(e);if(i!==void 0)throw new t(`Duplicate root command route '${e}' (${i.schema.name} and ${r.schema.name})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure root command names and aliases are unique`});n.set(e,r)};for(let t of e){r(t.schema.name,t);for(let e of t.schema.aliases)r(e,t)}return n}function l(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function u(e){return{command:e.command,mergedSchema:l(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function d(e,t,n,r,i,a){return{kind:`match`,plan:u({command:t,commandPath:n,argv:r,meta:s(e,i,t.schema.name),plugins:e.plugins,output:a,help:i})}}function f(e){let s=e.argv.indexOf(`--`),l=s===-1?e.argv:e.argv.slice(0,s),u=s===-1?[]:e.argv.slice(s),p=l.includes(`--json`)?l.filter(e=>e!==`--json`):l,m=s===-1?p:[...p,...u];if(e.schema.version!==void 0&&(i(e.argv,`--version`)||i(e.argv,`-V`)))return{kind:`root-version`,version:e.schema.version};let h=m[0];if(h===`--help`||h===`-h`)return{kind:`root-help`,help:e.help};if(h===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=m.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:f({...e,argv:[...t,`--help`]})}if(h===void 0&&e.schema.defaultCommand===void 0)return{kind:`root-help`,help:e.help};if(e.schema.commands.length===0)return{kind:`dispatch-error`,error:new t(`No commands registered`,{code:`NO_ACTION`,suggest:`Add commands via .command() before calling .run()`})};let g=e.schema.defaultCommand,_=g===void 0?void 0:r(g.schema.flags),v=a(m,c(e.schema.commands),[],_);switch(v.kind){case`unknown`:{if(g!==void 0&&v.parentPath.length===0&&(v.input===``?void 0:o(v.input,v.candidates))===void 0)return d(e.schema,g,[g.schema],m,e.help,e.output);if(v.input===``){let t=m.find(e=>e.startsWith(`-`));return t===void 0?{kind:`root-help`,help:e.help}:{kind:`dispatch-error`,error:new n(`Unknown flag ${t}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${e.schema.name} --help' for available commands`})}}let t=o(v.input,v.candidates),r=v.parentPath.length>0?`${e.schema.name} ${v.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${v.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=v.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:v.command,commandPath:v.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return d(e.schema,v.command,v.commandPath,v.remainingArgv,e.help,e.output)}}export{f as planInvocation};
@@ -13,6 +13,10 @@ interface CLISchemaLike {
13
13
  readonly defaultCommand: {
14
14
  readonly schema: CommandSchema;
15
15
  } | undefined;
16
+ readonly helpLinks?: {
17
+ readonly name: string | undefined;
18
+ readonly version: string | undefined;
19
+ } | undefined;
16
20
  }
17
21
  /**
18
22
  * Generate root-level help text for the CLI program.
@@ -1,7 +1,6 @@
1
- import{resolveRootSurface as e}from"./root-surface.mjs";import{formatHelpSections as t}from"../help/index.mjs";function n(n,a){let s=a?.width??80,c=e(n);if(c.hasSingleVisibleDefault){let e=c.visibleDefaultCommand;if(e!==void 0){let i=r(n,c.visibleCommands,c.visibleDefaultCommand,s),l=i.findIndex(e=>e.startsWith(`Usage: `)),u=[...t(e,{...a,binName:n.name,isDefaultHelp:!0})],d=u.shift();return l!==-1&&d!==void 0&&(i[l]=o(i[l]??``,d)),e.description!==void 0&&n.description!==void 0&&e.description===n.description&&u.shift(),i.push(...u),`${i.join(`
1
+ import{resolveRootSurface as e}from"./root-surface.mjs";import{osc8 as t,padEnd as n,wrapText as r}from"../help/ansi.mjs";import{formatHelpSections as i}from"../help/index.mjs";function a(t,n){let r=n?.width??80,a=n?.hyperlinks===!0,s=e(t);if(s.hasSingleVisibleDefault){let e=s.visibleDefaultCommand;if(e!==void 0){let c=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),l=c.findIndex(e=>e.startsWith(`Usage: `)),d=[...i(e,{...n,binName:t.name,isDefaultHelp:!0})],f=d.shift();return l!==-1&&f!==void 0&&(c[l]=u(c[l]??``,f)),e.description!==void 0&&t.description!==void 0&&e.description===t.description&&d.shift(),c.push(...d),`${c.join(`
2
2
 
3
- `)}\n`}}let l=r(n,c.visibleCommands,c.visibleDefaultCommand,s),u=i(c.visibleCommands,c.visibleDefaultCommand);return l.push(u.length>0?`Run '${n.name} ${u} --help' for more information.`:`Run '${n.name} --help' for more information.`),`${l.join(`
3
+ `)}\n`}}let l=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),d=c(s.visibleCommands,s.visibleDefaultCommand);return l.push(d.length>0?`Run '${t.name} ${d} --help' for more information.`:`Run '${t.name} --help' for more information.`),`${l.join(`
4
4
 
5
- `)}\n`}function r(e,t,n,r){let o=[],s=e.version===void 0?e.name:`${e.name} v${e.version}`;o.push(s),e.description!==void 0&&o.push(e.description);let c=i(t,n);return o.push(c.length>0?`Usage: ${e.name} ${c} [options]`:`Usage: ${e.name} [options]`),t.length>0&&o.push(a(t,n?.name,r)),o}function i(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function a(e,t,n){let r=[`Commands:`],i=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>i&&(i=r)}let a=2+i+2;for(let i of e){let e=s(` ${i.name===t?`${i.name} (default)`:i.name}`,a),o=i.description??``;o.length===0?r.push(e.trimEnd()):r.push(`${e}${c(o,n,a)}`)}return r.join(`
6
- `)}function o(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}function s(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function c(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
7
- `)}export{n as formatRootHelp};
5
+ `)}\n`}function o(e,t,n,r,i){let a=[];a.push(s(e,i)),e.description!==void 0&&a.push(e.description);let o=c(t,n);return a.push(o.length>0?`Usage: ${e.name} ${o} [options]`:`Usage: ${e.name} [options]`),t.length>0&&a.push(l(t,n?.name,r)),a}function s(e,n){let r=n?e.helpLinks:void 0,i=r?.name===void 0?e.name:t(r.name,e.name);if(e.version===void 0)return i;let a=`v${e.version}`;return`${i} ${r?.version===void 0?a:t(r.version,a)}`}function c(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function l(e,t,i){let a=[`Commands:`],o=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>o&&(o=r)}let s=2+o+2;for(let o of e){let e=n(` ${o.name===t?`${o.name} (default)`:o.name}`,s),c=o.description??``;c.length===0?a.push(e.trimEnd()):a.push(`${e}${r(c,i,s)}`)}return a.join(`
6
+ `)}function u(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}export{a as formatRootHelp};
@@ -5,6 +5,7 @@ import { CLIError } from "../errors/index.mjs";
5
5
  import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
7
  import { PackageJsonData } from "../config/package-json.mjs";
8
+ import { HelpLinks } from "./help-links.mjs";
8
9
  import { FormatLoader } from "../config/index.mjs";
9
10
 
10
11
  //#region src/core/cli/runtime-preflight.d.ts
@@ -48,6 +49,8 @@ interface RuntimePreflightSchemaLike {
48
49
  readonly configSettings: RuntimeConfigSettings | undefined;
49
50
  /** Package.json discovery settings; `undefined` disables package.json inference. */
50
51
  readonly packageJsonSettings: RuntimePackageJsonSettings | undefined;
52
+ /** Root-help header link targets; `undefined` fields may be derived from package.json. */
53
+ readonly helpLinks: HelpLinks | undefined;
51
54
  /** Whether `.completions()` registered the built-in completions command. */
52
55
  readonly hasBuiltInCompletions: boolean;
53
56
  /** Plugins forwarded into the execution pipeline. */
@@ -1 +1 @@
1
- import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=i.data??await a(t,i.from);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
1
+ import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{discoverPackageJson as i,inferCliName as a}from"../config/package-json.mjs";import{deriveHelpLinks as o}from"./help-links.mjs";import{planInvocation as s}from"./planner.mjs";import{discoverConfig as c}from"../config/index.mjs";const l={jsonMode:!1,isTTY:!1,verbosity:`normal`};function u(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function d(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function f(e,t){let n=s({schema:e,argv:t,help:{binName:e.name},output:l});switch(n.kind){case`match`:return d(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function p(e,t){if(!e.hasBuiltInCompletions)return!1;let n=s({schema:e,argv:t,help:{binName:e.name},output:l});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function m(e,t,n,r){let s=e.packageJsonSettings,c=s!==void 0&&!r?await(async()=>{let n=s.data??await i(t,s.from);if(n===null)return e;let r=s.inferName?a(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r},helpLinks:o(e.helpLinks,n,e.version??n.version)}})():e;return n===void 0?c:{...c,name:n}}async function h(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await c(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function g(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:u(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=p(t.schema,a),c=await m(t.schema,t.adapter,t.inheritedName,s),l=await h(c,t.adapter,i,s,t.options?.config);if(l instanceof e)return{kind:`config-error`,error:l,jsonMode:o};let d=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&f(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?d===void 0?{}:{prompter:d}:{prompter:t.options.prompter},...l===void 0?{}:{config:l}}}}export{g as prepareRuntimePreflight};
@@ -1,5 +1,5 @@
1
1
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
- import { PackageJsonAdapter, PackageJsonData, discoverPackageJson, inferCliName } from "./package-json.mjs";
2
+ import { PackageJsonAdapter, PackageJsonData, PackageRepository, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./package-json.mjs";
3
3
 
4
4
  //#region src/core/config/index.d.ts
5
5
  /**
@@ -158,4 +158,4 @@ declare function discoverConfig(appName: string, adapter: ConfigAdapter, options
158
158
  */
159
159
  declare function configFormat(extensions: readonly string[], parse: (content: string) => unknown): FormatLoader;
160
160
  //#endregion
161
- export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type PackageJsonAdapter, type PackageJsonData, buildConfigSearchPaths, configFormat, discoverConfig, discoverPackageJson, inferCliName };
161
+ export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, buildConfigSearchPaths, configFormat, discoverConfig, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -1,6 +1,18 @@
1
1
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
2
 
3
3
  //#region src/core/config/package-json.d.ts
4
+ /**
5
+ * Object form of the package.json `repository` field
6
+ * (e.g. `{"type":"git","url":"git+https://github.com/u/r.git"}`).
7
+ */
8
+ interface PackageRepository {
9
+ /** Version control system type (usually `'git'`). */
10
+ readonly type?: string;
11
+ /** Repository URL or locator. */
12
+ readonly url?: string;
13
+ /** Subdirectory within a monorepo where the package lives. */
14
+ readonly directory?: string;
15
+ }
4
16
  /**
5
17
  * Subset of package.json fields relevant to CLI metadata.
6
18
  *
@@ -15,6 +27,10 @@ interface PackageJsonData {
15
27
  readonly description?: string;
16
28
  /** Binary entry point(s) — string for single-bin, object for multi-bin. */
17
29
  readonly bin?: string | Readonly<Record<string, string>>;
30
+ /** Project homepage URL. */
31
+ readonly homepage?: string;
32
+ /** Repository locator — URL/shorthand string or `{type, url, directory}` object. */
33
+ readonly repository?: string | PackageRepository;
18
34
  }
19
35
  /**
20
36
  * The subset of {@link RuntimeAdapter} needed for package.json discovery.
@@ -55,6 +71,25 @@ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
55
71
  * ```
56
72
  */
57
73
  declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: string): Promise<PackageJsonData | null>;
74
+ /**
75
+ * Resolve a package's `repository` field to a browsable `https://` URL.
76
+ *
77
+ * Handles the locator formats npm accepts:
78
+ * - object form: `{ "type": "git", "url": "git+https://github.com/u/r.git" }`
79
+ * - `https`/`git`/`ssh` URLs (`git+` prefix and `.git` suffix stripped)
80
+ * - scp-style locators: `git@github.com:u/r.git`
81
+ * - shorthands: `github:u/r`, `gitlab:u/r`, `bitbucket:u/r`, and bare `u/r`
82
+ * (GitHub, per npm convention)
83
+ *
84
+ * Returns `undefined` when the field is absent or unrecognised.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * packageRepositoryUrl({ repository: 'git+https://github.com/u/r.git' });
89
+ * // 'https://github.com/u/r'
90
+ * ```
91
+ */
92
+ declare function packageRepositoryUrl(pkg: PackageJsonData): string | undefined;
58
93
  /**
59
94
  * Infer the CLI binary name from package.json data.
60
95
  *
@@ -75,4 +110,4 @@ declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: str
75
110
  */
76
111
  declare function inferCliName(pkg: PackageJsonData): string | undefined;
77
112
  //#endregion
78
- export { type PackageJsonAdapter, type PackageJsonData, discoverPackageJson, inferCliName };
113
+ export { type PackageJsonAdapter, type PackageJsonData, type PackageRepository, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -1 +1 @@
1
- function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e,r){let a=r??e.cwd;for(;a!==void 0;){let r=null;try{r=await e.readFile(n(a,`package.json`))}catch{}if(r!==null){let e=i(r);if(e!==null)return e}a=t(a)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,o=typeof n.description==`string`?n.description:void 0,s=a(n.bin);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...o===void 0?{}:{description:o},...s===void 0?{}:{bin:s}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,o as inferCliName};
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e,r){let a=r??e.cwd;for(;a!==void 0;){let r=null;try{r=await e.readFile(n(a,`package.json`))}catch{}if(r!==null){let e=i(r);if(e!==null)return e}a=t(a)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,s=typeof n.description==`string`?n.description:void 0,c=a(n.bin),l=typeof n.homepage==`string`?n.homepage:void 0,u=o(n.repository);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...s===void 0?{}:{description:s},...c===void 0?{}:{bin:c},...l===void 0?{}:{homepage:l},...u===void 0?{}:{repository:u}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(t){if(typeof t==`string`)return t;if(!e(t))return;let n=typeof t.type==`string`?t.type:void 0,r=typeof t.url==`string`?t.url:void 0,i=typeof t.directory==`string`?t.directory:void 0;if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{type:n},...r===void 0?{}:{url:r},...i===void 0?{}:{directory:i}}}const s={github:`https://github.com`,gitlab:`https://gitlab.com`,bitbucket:`https://bitbucket.org`};function c(e){return e.endsWith(`.git`)?e.slice(0,-4):e}function l(e){let t=typeof e.repository==`string`?e.repository:e.repository?.url;if(t===void 0)return;let n=t.trim();if(n.length===0)return;let r=/^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(n);if(r!==null&&r[1]!==void 0&&r[2]!==void 0){let e=s[r[1]];if(e!==void 0)return`${e}/${c(r[2])}`}if(/^[\w.-]+\/[\w.-]+$/.test(n))return`https://github.com/${c(n)}`;n.startsWith(`git+`)&&(n=n.slice(4));let i=/^git@([^:/]+):(.+)$/.exec(n);if(i!==null&&i[1]!==void 0&&i[2]!==void 0)return`https://${i[1]}/${c(i[2].replace(/\/+$/,``))}`;if(/^(?:https?|git|ssh):\/\//.test(n))try{let e=new URL(n),t=c(e.pathname.replace(/\/+$/,``));return`https://${e.hostname}${t}`}catch{return}}function u(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,u as inferCliName,l as packageRepositoryUrl};
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTestPrompter as r}from"../prompt/index.mjs";import{resolve as i}from"../resolve/index.mjs";async function a(a){let{argv:l,command:f,meta:p,options:m,out:h,schema:g}=a;try{if(d(l,`--help`)||d(l,`-h`)){let e=t(g,m?.help);return h.log(e),{exitCode:0,error:void 0}}let a=f.handler;if(a===void 0){let t=new e(`Command '${f.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${f.schema.name}' command`});return h.error(t.message),{exitCode:1,error:t}}await o(m?.plugins,{argv:l,command:g,meta:p,out:h});let _=n(g,l),v=m?.prompter??(m?.answers===void 0?void 0:r(m.answers)),y=await i(g,_,{...m?.stdinData===void 0?{}:{stdinData:m.stdinData},...m?.env===void 0?{}:{env:m.env},...m?.config===void 0?{}:{config:m.config},...v===void 0?{}:{prompter:v}}),b={args:y.args,flags:y.flags,deprecations:y.deprecations,command:g,meta:p,out:h};await s(m?.plugins,`afterResolve`,b);for(let e of y.deprecations)h.warn(u(e));return await s(m?.plugins,`beforeAction`,b),await c(f,a,y.flags,y.args,h,p),await s(m?.plugins,`afterAction`,b),{exitCode:0,error:void 0}}catch(t){if(t instanceof e)return m?.jsonMode===!0?h.json({error:t.toJSON()}):(h.error(t.message),t.suggest!==void 0&&h.error(`Suggestion: ${t.suggest}`)),{exitCode:t.exitCode,error:t};let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return m?.jsonMode===!0?h.json({error:n.toJSON()}):h.error(n.message),{exitCode:1,error:n}}finally{h.stopActive()}}async function o(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function s(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function c(t,n,r,i,a,o){let s=t._executionSteps,c=async e=>{await n({flags:r,args:i,ctx:e,out:a,meta:o})};for(let t=s.length-1;t>=0;t--){let n=s[t];if(n===void 0)continue;let l=c;switch(n.kind){case`derive`:c=async t=>{let s=await n.handler({args:i,flags:r,ctx:t,out:a,meta:o});if(s===void 0){await l(t);return}if(typeof s!=`object`||!s||Array.isArray(s))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...s})};break;case`middleware`:c=async e=>{await n.handler({args:i,flags:r,ctx:e,out:a,meta:o,next:async t=>{await l({...e,...t})}})};break}}await c({})}function l(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function u(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}function d(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}export{l as buildRunResult,a as executeCommand};
1
+ import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{includesBeforeSeparator as n,parse as r}from"../parse/index.mjs";import{createTestPrompter as i}from"../prompt/index.mjs";import{resolve as a}from"../resolve/index.mjs";async function o(o){let{argv:u,command:f,meta:p,options:m,out:h,schema:g}=o;try{if(n(u,`--help`)||n(u,`-h`)){let e=t(g,m?.help);return h.log(e),{exitCode:0,error:void 0}}let o=f.handler;if(o===void 0){let t=new e(`Command '${f.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${f.schema.name}' command`});return h.error(t.message),{exitCode:1,error:t}}await s(m?.plugins,{argv:u,command:g,meta:p,out:h});let _=r(g,u),v=m?.prompter??(m?.answers===void 0?void 0:i(m.answers)),y=await a(g,_,{...m?.stdinData===void 0?{}:{stdinData:m.stdinData},...m?.env===void 0?{}:{env:m.env},...m?.config===void 0?{}:{config:m.config},...v===void 0?{}:{prompter:v}}),b={args:y.args,flags:y.flags,deprecations:y.deprecations,command:g,meta:p,out:h};await c(m?.plugins,`afterResolve`,b);for(let e of y.deprecations)h.warn(d(e));return await c(m?.plugins,`beforeAction`,b),await l(f,o,y.flags,y.args,h,p),await c(m?.plugins,`afterAction`,b),{exitCode:0,error:void 0}}catch(t){if(t instanceof e)return m?.jsonMode===!0?h.json({error:t.toJSON()}):(h.error(t.message),t.suggest!==void 0&&h.error(`Suggestion: ${t.suggest}`)),{exitCode:t.exitCode,error:t};let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return m?.jsonMode===!0?h.json({error:n.toJSON()}):h.error(n.message),{exitCode:1,error:n}}finally{h.stopActive()}}async function s(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function c(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function l(t,n,r,i,a,o){let s=t._executionSteps,c=async e=>{await n({flags:r,args:i,ctx:e,out:a,meta:o})};for(let t=s.length-1;t>=0;t--){let n=s[t];if(n===void 0)continue;let l=c;switch(n.kind){case`derive`:c=async t=>{let s=await n.handler({args:i,flags:r,ctx:t,out:a,meta:o});if(s===void 0){await l(t);return}if(typeof s!=`object`||!s||Array.isArray(s))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...s})};break;case`middleware`:c=async e=>{await n.handler({args:i,flags:r,ctx:e,out:a,meta:o,next:async t=>{await l({...e,...t})}})};break}}await c({})}function u(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function d(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}export{u as buildRunResult,o as executeCommand};
@@ -0,0 +1,78 @@
1
+ //#region src/core/help/ansi.d.ts
2
+ /**
3
+ * ANSI/OSC-aware text helpers for help formatting.
4
+ *
5
+ * Terminal escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero
6
+ * columns when rendered, so width math must measure the *visible* text.
7
+ * {@linkcode visibleWidth} strips escapes before counting, and the shared
8
+ * {@linkcode padEnd}/{@linkcode wrapText} helpers build on it so aligned
9
+ * tables and wrapped lines stay intact when escapes are present.
10
+ *
11
+ * @module dreamcli/core/help/ansi
12
+ */
13
+ /**
14
+ * Remove ANSI CSI and OSC escape sequences from `text`.
15
+ *
16
+ * @param text - Text possibly containing terminal escapes.
17
+ * @returns The text with all escape sequences removed.
18
+ */
19
+ declare function stripAnsi(text: string): string;
20
+ /**
21
+ * Measure the visible column width of `text`, ignoring ANSI/OSC escapes.
22
+ *
23
+ * Escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero columns when
24
+ * rendered, so `.length` overcounts whenever they are present. Help
25
+ * formatting uses this for padding and wrapping; exported for custom help
26
+ * renderers that mix colors or links into aligned output.
27
+ *
28
+ * @param text - Text possibly containing terminal escapes.
29
+ * @returns Number of visible characters.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * visibleWidth('plain'); // 5
34
+ * visibleWidth(osc8('https://x.dev', 'x')); // 1
35
+ * ```
36
+ */
37
+ declare function visibleWidth(text: string): number;
38
+ /**
39
+ * Wrap `text` in an [OSC 8 hyperlink](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
40
+ * pointing at `url`.
41
+ *
42
+ * Supporting terminals render `text` as a clickable link; non-supporting
43
+ * terminals ignore the escape sequence and show plain text. Combine with
44
+ * {@linkcode visibleWidth}-aware formatting when embedding links in aligned
45
+ * output.
46
+ *
47
+ * @param url - Link target (string or `URL` instance).
48
+ * @param text - Visible link text.
49
+ * @returns The OSC 8 escape sequence wrapping `text`.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * cli('mycli').version(osc8('https://github.com/me/mycli/releases/tag/v1.0.0', '1.0.0'));
54
+ * ```
55
+ */
56
+ declare function osc8(url: string | URL, text: string): string;
57
+ /**
58
+ * Pad `text` to `length` visible columns with trailing spaces.
59
+ *
60
+ * @param text - The string to pad (may contain ANSI/OSC escapes).
61
+ * @param length - Target visible width in columns.
62
+ * @returns The padded string, unchanged if already at or beyond `length`.
63
+ */
64
+ declare function padEnd(text: string, length: number): string;
65
+ /**
66
+ * Wrap text to `width`, preserving leading indent on continuation lines.
67
+ *
68
+ * Line lengths are measured with {@linkcode visibleWidth}, so embedded
69
+ * ANSI/OSC escapes do not trigger premature wrapping.
70
+ *
71
+ * @param text - The text to wrap.
72
+ * @param width - Maximum line width in columns.
73
+ * @param indent - Number of leading spaces for continuation lines.
74
+ * @returns The wrapped string with newlines inserted as needed.
75
+ */
76
+ declare function wrapText(text: string, width: number, indent: number): string;
77
+ //#endregion
78
+ export { osc8, padEnd, stripAnsi, visibleWidth, wrapText };
@@ -0,0 +1,2 @@
1
+ const e=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function t(t){return t.replace(e,``)}function n(e){return t(e).length}function r(e,t){return`]8;;${e instanceof URL?e.href:e}${t}]8;;`}function i(e,t){let r=n(e);return r>=t?e:e+` `.repeat(t-r)}function a(e,t,r){if(n(e)+r<=t)return e;let i=t-r;if(i<=0)return e;let a=e.split(` `),o=[],s=``,c=0;for(let e of a){let t=n(e);s.length===0?(s=e,c=t):c+1+t<=i?(s+=` ${e}`,c+=1+t):(o.push(s),s=e,c=t)}s.length>0&&o.push(s);let l=` `.repeat(r);return o.map((e,t)=>t===0?e:`${l}${e}`).join(`
2
+ `)}export{r as osc8,i as padEnd,n as visibleWidth,a as wrapText};
@@ -1,3 +1,4 @@
1
+ import { osc8, visibleWidth } from "./ansi.mjs";
1
2
  import { CommandSchema } from "../schema/command.mjs";
2
3
 
3
4
  //#region src/core/help/index.d.ts
@@ -7,6 +8,13 @@ interface HelpOptions {
7
8
  readonly width?: number;
8
9
  /** Binary/program name shown in the usage line. Defaults to command name. */
9
10
  readonly binName?: string;
11
+ /**
12
+ * Emit OSC 8 hyperlinks where link metadata is available (currently the
13
+ * root-help header name/version configured via `CLIBuilder.links()`).
14
+ * Defaults to `false`; `CLIBuilder.execute()`/`.run()` enable it
15
+ * automatically when stdout is a TTY.
16
+ */
17
+ readonly hyperlinks?: boolean;
10
18
  /** @internal Whether this usage line is being rendered as merged root/default help. */
11
19
  readonly isDefaultHelp?: boolean;
12
20
  }
@@ -46,4 +54,4 @@ declare function formatHelpSections(schema: CommandSchema, options?: HelpOptions
46
54
  */
47
55
  declare function formatHelp(schema: CommandSchema, options?: HelpOptions): string;
48
56
  //#endregion
49
- export { type HelpOptions, formatHelp, formatHelpSections };
57
+ export { type HelpOptions, formatHelp, formatHelpSections, osc8, visibleWidth };