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

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 (137) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.d.mts +7 -3
  66. package/dist/version.mjs +7 -1
  67. package/package.json +21 -26
  68. package/src/core/cli/dispatch.ts +0 -355
  69. package/src/core/cli/help-links.ts +0 -82
  70. package/src/core/cli/index.ts +0 -1614
  71. package/src/core/cli/planner.ts +0 -656
  72. package/src/core/cli/plugin.ts +0 -117
  73. package/src/core/cli/propagate.ts +0 -97
  74. package/src/core/cli/root-help.ts +0 -342
  75. package/src/core/cli/root-surface.ts +0 -87
  76. package/src/core/cli/runtime-preflight.ts +0 -456
  77. package/src/core/completion/index.ts +0 -138
  78. package/src/core/completion/shells/bash.ts +0 -459
  79. package/src/core/completion/shells/fish.ts +0 -259
  80. package/src/core/completion/shells/powershell.ts +0 -439
  81. package/src/core/completion/shells/shared.ts +0 -310
  82. package/src/core/completion/shells/zsh.ts +0 -381
  83. package/src/core/config/index.ts +0 -417
  84. package/src/core/config/package-json.ts +0 -560
  85. package/src/core/errors/index.ts +0 -193
  86. package/src/core/execution/index.ts +0 -265
  87. package/src/core/help/ansi.ts +0 -144
  88. package/src/core/help/index.ts +0 -563
  89. package/src/core/json-schema/index.ts +0 -910
  90. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  91. package/src/core/output/activity.ts +0 -575
  92. package/src/core/output/bind.ts +0 -59
  93. package/src/core/output/contracts.ts +0 -194
  94. package/src/core/output/display-value.ts +0 -48
  95. package/src/core/output/index.ts +0 -704
  96. package/src/core/output/renderers.ts +0 -125
  97. package/src/core/output/writer.ts +0 -46
  98. package/src/core/parse/index.ts +0 -742
  99. package/src/core/prompt/index.ts +0 -623
  100. package/src/core/resolve/args.ts +0 -144
  101. package/src/core/resolve/coerce.ts +0 -500
  102. package/src/core/resolve/config.ts +0 -26
  103. package/src/core/resolve/contracts.ts +0 -135
  104. package/src/core/resolve/errors.ts +0 -227
  105. package/src/core/resolve/flags.ts +0 -269
  106. package/src/core/resolve/index.ts +0 -108
  107. package/src/core/resolve/property.ts +0 -99
  108. package/src/core/schema/activity.ts +0 -240
  109. package/src/core/schema/arg.ts +0 -841
  110. package/src/core/schema/command.ts +0 -1500
  111. package/src/core/schema/flag.ts +0 -917
  112. package/src/core/schema/index.ts +0 -96
  113. package/src/core/schema/middleware.ts +0 -171
  114. package/src/core/schema/number-constraints.ts +0 -153
  115. package/src/core/schema/prompt.ts +0 -171
  116. package/src/core/schema/run.ts +0 -198
  117. package/src/core/schema-dsl/index.ts +0 -109
  118. package/src/core/schema-dsl/parse.ts +0 -262
  119. package/src/core/schema-dsl/runtime.ts +0 -609
  120. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  121. package/src/core/testkit/index.ts +0 -147
  122. package/src/index.ts +0 -181
  123. package/src/runtime/adapter.ts +0 -303
  124. package/src/runtime/auto.ts +0 -86
  125. package/src/runtime/bun.ts +0 -48
  126. package/src/runtime/deno.ts +0 -367
  127. package/src/runtime/detect.ts +0 -105
  128. package/src/runtime/index.ts +0 -21
  129. package/src/runtime/node-builtins.d.ts +0 -27
  130. package/src/runtime/node.ts +0 -289
  131. package/src/runtime/paths.ts +0 -64
  132. package/src/runtime/support.ts +0 -77
  133. package/src/runtime.ts +0 -31
  134. package/src/schema.ts +0 -16
  135. package/src/strings.ts +0 -34
  136. package/src/testkit.ts +0 -25
  137. package/src/version.ts +0 -20
@@ -1 +1,901 @@
1
- import{getFlagAliasNames as e}from"../schema/flag.mjs";import{CLIError as t}from"../errors/index.mjs";import{SHELLS as n,detectShell as r,generateCompletion as i,normalizeShell as a}from"../completion/index.mjs";import{formatHelp as o}from"../help/index.mjs";import{clearRequestedExitCode as s,createCaptureOutput as c,createOutput as l}from"../output/index.mjs";import{arg as u}from"../schema/arg.mjs";import{command as d}from"../schema/command.mjs";import{includesBeforeSeparator as f}from"../parse/index.mjs";import{buildRunResult as p,executeCommand as m}from"../execution/index.mjs";import{runCommand as h}from"../testkit/index.mjs";import{stripTrailing as g}from"../../strings.mjs";import{createAdapter as _}from"../../runtime/auto.mjs";import{deriveHelpLinks as v}from"./help-links.mjs";import{planInvocation as y}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as b}from"./root-help.mjs";import{prepareRuntimePreflight as x}from"./runtime-preflight.mjs";const S=`completions`;function C(t){if(Object.hasOwn(t.flags,S))return!0;for(let n of Object.values(t.flags))if(e(n,{kind:`long`,includeHidden:!0}).includes(S))return!0;return t.commands.some(C)}function w(e){if(C(e))throw new t(`Command '${e.name}' defines a '--${S}' flag, which is reserved by .completions({ as: 'flag' })`,{code:`RESERVED_FLAG`,suggest:`Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`})}function T(e){return[e.name,...e.aliases]}function E(e,n,r,i){let a=n.get(r);if(a!==void 0)throw new t(`Duplicate command route '${r}' under '${e}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function D(e,n,r){let i=new Map,a=r===void 0?e:[...e,r];for(let e of a)for(let t of T(e.schema))E(`root`,i,t,e.schema.name);for(let e of T(n)){let r=i.get(e);if(r!==void 0)throw new t(`Command route '${e}' is already registered by '${r}'`,{code:`DUPLICATE_COMMAND`,suggest:r===n.name?`Ensure command '${n.name}' does not reuse route '${e}'`:`Rename '${n.name}' or remove route '${e}' from '${r}'`});i.set(e,n.name)}}function O(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=T(r.schema);for(let t of i)E(e.schema.name,n,t,r.schema.name);let a=O(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return h(e,t,n)}}}function k(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 A=class e{schema;constructor(e){this.schema=e}version(t){return new e({...this.schema,version:t})}description(t){return new e({...this.schema,description:t})}links(t){return new e({...this.schema,helpLinks:{name:F(t?.name),version:F(t?.version)}})}help(t){return new e({...this.schema,helpConfig:{...this.schema.helpConfig,...t}})}config(t,n){return new e({...this.schema,configSettings:{appName:t,loaders:n}})}configLoader(n){if(this.schema.configSettings===void 0)throw new t(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let r=this.schema.configSettings.loaders??[];return new e({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...r,n]}})}manifest(t){return new e(B(this.schema,t,L,!1))}packageJson(t){return new e(B(this.schema,t,L,!0))}denoJson(t){return new e(B(this.schema,t,R,!0))}command(t){return D(this.schema.commands,t.schema,this.schema.defaultCommand),this.schema.completionsFlag!==void 0&&w(t.schema),new e({...this.schema,commands:[...this.schema.commands,O(t)]})}default(n){if(this.schema.defaultCommand!==void 0)throw new t(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});D(this.schema.commands,n.schema),this.schema.completionsFlag!==void 0&&w(n.schema);let r=O(n);return new e({...this.schema,defaultCommand:r})}plugin(t){return new e({...this.schema,plugins:[...this.schema.plugins,t]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new t(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});if(r?.as===`flag`){this.schema.defaultCommand!==void 0&&w(this.schema.defaultCommand.schema);for(let e of this.schema.commands)w(e.schema);return new e({...this.schema,hasBuiltInCompletions:!0,completionsFlag:{shells:n,options:r}})}let o=this.schema,s=r,c=d(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,u.custom(e=>{let t=a(e);if(t===void 0)throw Error(`Unknown shell '${e}'. Valid shells: ${n.join(`, `)}`);return t}).env(`SHELL`).describe(`Target shell (${n.join(`, `)})`)).action(({args:e,meta:t,out:n})=>{let r=i(t.bin===o.name?o:{...o,name:t.bin},e.shell,s);n.jsonMode?n.json({shell:e.shell,script:r}):n.log(r)});return new e({...this.command(c).schema,hasBuiltInCompletions:!0})}async execute(e,n){let a=f(e,`--json`)||n?.jsonMode===!0,l={...n?.verbosity===void 0?{}:{verbosity:n.verbosity},...a?{jsonMode:a}:{},...n?.isTTY===void 0?{}:{isTTY:n.isTTY}},u,d;n?.out===void 0?[u,d]=c(Object.keys(l).length>0?l:void 0):(u=n.out,d=n.captured??{stdout:[],stderr:[],activity:[]}),s(u);let h={...this.schema.helpConfig,...n?.help,binName:n?.help?.binName??this.schema.name,hyperlinks:n?.help?.hyperlinks??this.schema.helpConfig?.hyperlinks??u.isTTY},g={...n,plugins:this.schema.plugins,...a?{jsonMode:a}:{}},_={jsonMode:a,isTTY:u.isTTY,verbosity:n?.verbosity??`normal`},v=y({schema:this.schema,argv:e,help:h,output:_});switch(v.kind){case`root-version`:return u.log(v.version),p({exitCode:0,error:void 0},d);case`root-completions`:{let e=v.shell??r(n?.env??{});if(e===void 0){let e=new t(`Could not detect shell`,{code:`MISSING_VALUE`,suggest:`Pass one explicitly, e.g. '${h.binName} --completions zsh'`});return a?u.json({error:e.toJSON()}):(u.error(e.message),u.error(`Suggestion: ${e.suggest}`)),p({exitCode:e.exitCode,error:e},d)}let o=i(h.binName===void 0||h.binName===this.schema.name?this.schema:{...this.schema,name:h.binName},e,v.options);return a?u.json({shell:e,script:o}):u.log(o),p({exitCode:0,error:void 0},d)}case`root-help`:{let e=b(I(this.schema),v.help);return u.log(e),p({exitCode:0,error:void 0},d)}case`dispatch-error`:return a?u.json({error:v.error.toJSON()}):(u.error(v.error.message),v.error.suggest!==void 0&&v.error.code!==`NO_ACTION`&&u.error(`Suggestion: ${v.error.suggest}`)),p({exitCode:v.error.exitCode,error:v.error},d);case`needs-subcommand`:{let e=o(v.command.schema,v.help);return u.log(e),p({exitCode:0,error:void 0},d)}case`match`:{let e=k(g,v.plan.help??h,v.plan.meta);return v.plan.command._command===void 0?v.plan.command._execute(v.plan.argv,{...e,mergedSchema:v.plan.mergedSchema}):p(await m({command:v.plan.command._command,argv:v.plan.argv,out:u,schema:v.plan.mergedSchema,meta:v.plan.meta,options:e}),d)}}}async run(t){let n=t?.adapter??_(),r=this.schema.inheritName?P(n.argv):void 0,i=await x({schema:this.schema,adapter:n,options:t,inheritedName:r});if(i.kind===`config-error`)return i.jsonMode?n.stdout(`${JSON.stringify({error:i.error.toJSON()})}\n`):(n.stderr(`Error: ${i.error.message}\n`),i.error.suggest!==void 0&&n.stderr(`Suggestion: ${i.error.suggest}\n`)),n.exit(i.error.exitCode);let a=i.schema===this.schema?this:new e(i.schema),o={...t,...i.inputs,out:l({stdout:n.stdout,stderr:n.stderr,jsonMode:i.inputs.jsonMode,isTTY:i.inputs.isTTY,...i.inputs.verbosity===`normal`?{}:{verbosity:i.inputs.verbosity}})},s=await a.execute(i.filteredArgv,o);for(let e of s.stdout)n.stdout(e);for(let e of s.stderr)n.stderr(e);return n.exit(s.exitCode)}};const j=new Set([`bun`,`deno`,`node`,`tsx`]);function M(e){let t=g(e,[47,92]);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 N(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return j.has(t)}function P(e){let t=e[0],n=e[1],r=t===void 0?void 0:M(t);if(r!==void 0&&N(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:M(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:M(n)}return t===void 0?void 0:M(t)}function F(e){if(e!==void 0)return e instanceof URL?e.href:e}function I(e){return e.helpLinks===void 0?e:{...e,helpLinks:v(e.helpLinks,e.packageJsonSettings?.data,e.version)}}const L=[`package.json`],R=[`deno.json`,`deno.jsonc`,`jsr.json`];function z(e){return e===void 0||e===!1?{inferName:!1,stripScope:!0}:e===!0?{inferName:!0,stripScope:!0}:{inferName:!0,stripScope:e.scope!==`keep`}}function B(e,t,n,r){if(H(t))return{...e,...e.version===void 0&&t.version!==void 0?{version:t.version}:{},...e.description===void 0&&t.description!==void 0?{description:t.description}:{},packageJsonSettings:{inferName:!1,stripScope:!0,from:void 0,files:n,data:t}};let{inferName:i,stripScope:a}=z(t?.inferName),o=r?n:t?.files??n;return{...e,packageJsonSettings:{inferName:i,stripScope:a,from:V(t?.from),files:o,data:void 0}}}function V(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 H(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 U(e){return new A({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,completionsFlag:void 0,helpConfig:void 0,plugins:[]})}export{A as CLIBuilder,U as cli};
1
+ import { getFlagAliasNames } from "../schema/flag.mjs";
2
+ import { CLIError } from "../errors/index.mjs";
3
+ import { SHELLS, detectShell, generateCompletion, normalizeShell } from "../completion/index.mjs";
4
+ import { formatHelp } from "../help/index.mjs";
5
+ import { clearRequestedExitCode, createCaptureOutput, createOutput } from "../output/index.mjs";
6
+ import { arg } from "../schema/arg.mjs";
7
+ import { command } from "../schema/command.mjs";
8
+ import { includesBeforeSeparator } from "../parse/index.mjs";
9
+ import { buildRunResult, executeCommand } from "../execution/index.mjs";
10
+ import { runCommand } from "../testkit/index.mjs";
11
+ import { stripTrailing } from "../../strings.mjs";
12
+ import { createAdapter } from "../../runtime/auto.mjs";
13
+ import { deriveHelpLinks } from "./help-links.mjs";
14
+ import { planInvocation } from "./planner.mjs";
15
+ import "./plugin.mjs";
16
+ import { formatRootHelp } from "./root-help.mjs";
17
+ import { prepareRuntimePreflight } from "./runtime-preflight.mjs";
18
+ //#region src/core/cli/index.ts
19
+ /** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
20
+ const COMPLETIONS_FLAG_NAME = "completions";
21
+ /**
22
+ * Whether a command — or any of its nested subcommands — declares a flag that
23
+ * collides with the eager `--completions` flag, by canonical name or long alias.
24
+ *
25
+ * @internal
26
+ */
27
+ function commandReservesCompletionsFlag(schema) {
28
+ if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
29
+ for (const flagSchema of Object.values(schema.flags)) if (getFlagAliasNames(flagSchema, {
30
+ kind: "long",
31
+ includeHidden: true
32
+ }).includes(COMPLETIONS_FLAG_NAME)) return true;
33
+ return schema.commands.some(commandReservesCompletionsFlag);
34
+ }
35
+ /**
36
+ * Reject a command whose flags would be shadowed by the eager `--completions`
37
+ * flag once `.completions({ as: 'flag' })` is active. Because the planner
38
+ * intercepts `--completions` before dispatch, such a flag could never be reached.
39
+ *
40
+ * @internal
41
+ */
42
+ function assertNoCompletionsFlagCollision(schema) {
43
+ if (commandReservesCompletionsFlag(schema)) throw new CLIError(`Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`, {
44
+ code: "RESERVED_FLAG",
45
+ suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`
46
+ });
47
+ }
48
+ function commandRoutes(schema) {
49
+ return [schema.name, ...schema.aliases];
50
+ }
51
+ function assertNoSiblingRouteConflict(parentCommandName, routeOwners, route, commandName) {
52
+ const owner = routeOwners.get(route);
53
+ if (owner !== void 0) throw new CLIError(`Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`, {
54
+ code: "DUPLICATE_COMMAND",
55
+ suggest: "Ensure sibling command names and aliases are unique"
56
+ });
57
+ routeOwners.set(route, commandName);
58
+ }
59
+ function assertNoTopLevelRouteConflict(commands, incoming, defaultCommand) {
60
+ const routeOwners = /* @__PURE__ */ new Map();
61
+ const existing = defaultCommand !== void 0 ? [...commands, defaultCommand] : commands;
62
+ for (const command of existing) for (const route of commandRoutes(command.schema)) assertNoSiblingRouteConflict("root", routeOwners, route, command.schema.name);
63
+ for (const route of commandRoutes(incoming)) {
64
+ const owner = routeOwners.get(route);
65
+ if (owner !== void 0) throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
66
+ code: "DUPLICATE_COMMAND",
67
+ suggest: owner === incoming.name ? `Ensure command '${incoming.name}' does not reuse route '${route}'` : `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`
68
+ });
69
+ routeOwners.set(route, incoming.name);
70
+ }
71
+ }
72
+ /**
73
+ * Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
74
+ * building the subcommand tree.
75
+ *
76
+ * The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
77
+ * the original `CommandBuilder<F, A>` — no type assertions needed.\
78
+ * Subcommands are recursively erased and indexed by name and alias for
79
+ * O(1) lookup during dispatch.
80
+ *
81
+ * @internal
82
+ */
83
+ function eraseCommand(cmd) {
84
+ const subcommands = /* @__PURE__ */ new Map();
85
+ const routeOwners = /* @__PURE__ */ new Map();
86
+ for (const sub of cmd._subcommands) {
87
+ const routes = commandRoutes(sub.schema);
88
+ for (const route of routes) assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
89
+ const erased = eraseCommand(sub);
90
+ for (const route of routes) subcommands.set(route, erased);
91
+ }
92
+ return {
93
+ schema: cmd.schema,
94
+ subcommands,
95
+ _command: cmd,
96
+ _execute(argv, options) {
97
+ return runCommand(cmd, argv, options);
98
+ }
99
+ };
100
+ }
101
+ /**
102
+ * Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
103
+ * field to satisfy `exactOptionalPropertyTypes`.
104
+ *
105
+ * @param options - CLI-level run options (may be `undefined` for defaults).
106
+ * @param helpOptions - Help formatting options forwarded to commands.
107
+ * @param meta - Optional command metadata (omitted for root-level dispatch).
108
+ * @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
109
+ *
110
+ * @internal
111
+ */
112
+ function buildCommandRunOptions(options, helpOptions, meta) {
113
+ return {
114
+ help: helpOptions,
115
+ ...meta !== void 0 ? { meta } : {},
116
+ ...options?.plugins !== void 0 ? { plugins: options.plugins } : {},
117
+ ...options?.env !== void 0 ? { env: options.env } : {},
118
+ ...options?.config !== void 0 ? { config: options.config } : {},
119
+ ...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
120
+ ...options?.prompter !== void 0 ? { prompter: options.prompter } : {},
121
+ ...options?.answers !== void 0 ? { answers: options.answers } : {},
122
+ ...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
123
+ ...options?.jsonMode !== void 0 ? { jsonMode: options.jsonMode } : {},
124
+ ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
125
+ ...options?.out !== void 0 ? { out: options.out } : {},
126
+ ...options?.captured !== void 0 ? { captured: options.captured } : {}
127
+ };
128
+ }
129
+ /**
130
+ * Immutable CLI program builder.
131
+ *
132
+ * Registers commands, handles root-level `--help`/`--version`, and
133
+ * dispatches to the matched command based on argv.
134
+ *
135
+ * Two execution paths:
136
+ * - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
137
+ * - `.run(options?)` — production entry, reads `process.argv`, exits process
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * import { cli, command, flag, arg } from '@kjanat/dreamcli';
142
+ *
143
+ * const deploy = command('deploy')
144
+ * .arg('target', arg.string())
145
+ * .flag('force', flag.boolean().alias('f'))
146
+ * .action(({ args, flags, out }) => {
147
+ * out.log(`Deploying ${args.target}...`);
148
+ * });
149
+ *
150
+ * cli('mycli')
151
+ * .version('1.0.0')
152
+ * .command(deploy)
153
+ * .run();
154
+ * ```
155
+ */
156
+ var CLIBuilder = class CLIBuilder {
157
+ /** @internal Runtime schema descriptor. */
158
+ schema;
159
+ /** Build a CLIBuilder from a pre-constructed schema descriptor. */
160
+ constructor(schema) {
161
+ this.schema = schema;
162
+ }
163
+ /**
164
+ * Set the program version (shown by `--version`).
165
+ *
166
+ * @param v - Semantic version string.
167
+ * @returns The builder (for chaining).
168
+ */
169
+ version(v) {
170
+ return new CLIBuilder({
171
+ ...this.schema,
172
+ version: v
173
+ });
174
+ }
175
+ /**
176
+ * Set the program description (shown in root help).
177
+ *
178
+ * @param text - Short description displayed in root help output.
179
+ * @returns The builder (for chaining).
180
+ */
181
+ description(text) {
182
+ return new CLIBuilder({
183
+ ...this.schema,
184
+ description: text
185
+ });
186
+ }
187
+ /**
188
+ * Make the root-help header clickable with OSC 8 hyperlinks.
189
+ *
190
+ * Links the program name and version on the first line of root `--help`
191
+ * output in terminals that support
192
+ * [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
193
+ * The escapes are only emitted when stdout is a TTY (overridable via
194
+ * `options.help.hyperlinks`), and only in the header — usage lines, the
195
+ * `--help` hint, the commands table, and completion scripts stay plain.
196
+ *
197
+ * URLs not provided here are derived from manifest metadata when
198
+ * `.manifest()` is active (works with both filesystem discovery and
199
+ * pre-loaded data):
200
+ * - **name** → normalized `repository` URL, falling back to `homepage`
201
+ * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
202
+ * GitHub, `{repo}/-/releases/v{version}` on GitLab)
203
+ *
204
+ * @param links - Explicit URLs; omit to derive everything from the manifest.
205
+ * @returns The builder (for chaining).
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * // Derive both links from the manifest repository/homepage:
210
+ * cli('mycli')
211
+ * .manifest()
212
+ * .links()
213
+ * .run();
214
+ *
215
+ * // Explicit URLs (no package.json required):
216
+ * cli('mycli')
217
+ * .version('1.0.0')
218
+ * .links({
219
+ * name: 'https://github.com/me/mycli',
220
+ * version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
221
+ * })
222
+ * .run();
223
+ * ```
224
+ */
225
+ links(links) {
226
+ return new CLIBuilder({
227
+ ...this.schema,
228
+ helpLinks: {
229
+ name: toUrlString(links?.name),
230
+ version: toUrlString(links?.version)
231
+ }
232
+ });
233
+ }
234
+ /**
235
+ * Configure root-help rendering defaults.
236
+ *
237
+ * Stored on the schema and merged **under** any runtime `options.help`
238
+ * (runtime wins). Call multiple times to set fields incrementally.
239
+ *
240
+ * @param config - Help rendering options (see {@link HelpConfig}).
241
+ * @returns The builder (for chaining).
242
+ *
243
+ * @example
244
+ * ```ts
245
+ * // Echo the default command under Commands and never show the footer:
246
+ * cli('mycli')
247
+ * .help({ showDefaultInCommands: true, footer: false })
248
+ * .default(serve)
249
+ * .run();
250
+ * ```
251
+ */
252
+ help(config) {
253
+ return new CLIBuilder({
254
+ ...this.schema,
255
+ helpConfig: {
256
+ ...this.schema.helpConfig,
257
+ ...config
258
+ }
259
+ });
260
+ }
261
+ /**
262
+ * Enable automatic config file discovery.
263
+ *
264
+ * When enabled, `.run()` probes standard paths before dispatching:
265
+ * 1. `$CWD/.{appName}.json`
266
+ * 2. `$CWD/{appName}.config.json`
267
+ * 3. `$CONFIG_DIR/{appName}/config.json`
268
+ * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
269
+ * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
270
+ *
271
+ * The user can override the path via `--config <path>` or `--config=<path>`.
272
+ *
273
+ * Loaded config feeds into the resolution chain
274
+ * (CLI → env → **config** → prompt → default) for flags that
275
+ * declare `.config('dotted.path')`.
276
+ *
277
+ * Has no effect in `.execute()` (which receives config via
278
+ * `options.config` directly).
279
+ *
280
+ * @param appName - Name used to build search paths.
281
+ * @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
282
+ * @returns The builder (for chaining).
283
+ */
284
+ config(appName, loaders) {
285
+ return new CLIBuilder({
286
+ ...this.schema,
287
+ configSettings: {
288
+ appName,
289
+ loaders
290
+ }
291
+ });
292
+ }
293
+ /**
294
+ * Register a custom config format loader.
295
+ *
296
+ * Adds a {@link FormatLoader} incrementally — call multiple times to
297
+ * register multiple formats. Loaders registered later for the same
298
+ * extension override earlier ones.
299
+ *
300
+ * Requires `.config()` to have been called first (sets the app name).
301
+ *
302
+ * @param loader - Format loader (or extensions + parse function).
303
+ * @returns The builder (for chaining).
304
+ *
305
+ * @example Bun built-in parsers
306
+ * ```ts
307
+ * import { configFormat } from '@kjanat/dreamcli';
308
+ *
309
+ * cli('myapp')
310
+ * .config('myapp')
311
+ * .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
312
+ * .configLoader(configFormat(['toml'], Bun.TOML.parse))
313
+ * .run();
314
+ * ```
315
+ *
316
+ * @example npm package parsers
317
+ * ```ts
318
+ * import { configFormat } from '@kjanat/dreamcli';
319
+ * import { parse as parseYaml } from 'yaml';
320
+ * import { parse as parseTOML } from '@iarna/toml';
321
+ *
322
+ * cli('myapp')
323
+ * .config('myapp')
324
+ * .configLoader(configFormat(['yaml', 'yml'], parseYaml))
325
+ * .configLoader(configFormat(['toml'], parseTOML))
326
+ * .run();
327
+ * ```
328
+ */
329
+ configLoader(loader) {
330
+ if (this.schema.configSettings === void 0) throw new CLIError(".configLoader() requires .config() to be called first", {
331
+ code: "INVALID_BUILDER_STATE",
332
+ suggest: "Call .config(appName) before .configLoader()"
333
+ });
334
+ const existing = this.schema.configSettings.loaders ?? [];
335
+ return new CLIBuilder({
336
+ ...this.schema,
337
+ configSettings: {
338
+ ...this.schema.configSettings,
339
+ loaders: [...existing, loader]
340
+ }
341
+ });
342
+ }
343
+ manifest(input) {
344
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
345
+ }
346
+ packageJson(input) {
347
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
348
+ }
349
+ denoJson(input) {
350
+ return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
351
+ }
352
+ /**
353
+ * Register a command with the CLI program.
354
+ *
355
+ * The command's type parameters are erased for heterogeneous storage.
356
+ * Type safety is preserved inside the closure that delegates to
357
+ * {@linkcode runCommand | runCommand()}.
358
+ *
359
+ * @param cmd - {@link CommandBuilder} to register.
360
+ * @returns The builder (for chaining).
361
+ */
362
+ command(cmd) {
363
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
364
+ if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
365
+ return new CLIBuilder({
366
+ ...this.schema,
367
+ commands: [...this.schema.commands, eraseCommand(cmd)]
368
+ });
369
+ }
370
+ /**
371
+ * Register a command as the default — dispatched when no subcommand is given.
372
+ *
373
+ * The CLI root behaves like a hybrid command group: named subcommands
374
+ * dispatch normally, but empty argv or flags-only argv falls through to
375
+ * this command instead of showing root help.
376
+ *
377
+ * The default command is the CLI's root *surface*: its flags and arguments
378
+ * are rendered inline in root help. It is **not** a named subcommand — it
379
+ * cannot be invoked by its own name (`mycli mycmd` does not route to it) and
380
+ * it is omitted from the root `Commands:` list by default (re-enable with
381
+ * `.help({ showDefaultInCommands: true })`). Only one default is allowed.
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * // Single-command CLI — no subcommand name needed:
386
+ * // mytool --force production
387
+ * cli('mytool')
388
+ * .default(deploy)
389
+ * .run();
390
+ *
391
+ * // Multi-command CLI with a default:
392
+ * // mytool production → runs deploy
393
+ * // mytool status → runs status
394
+ * cli('mytool')
395
+ * .default(deploy)
396
+ * .command(status)
397
+ * .run();
398
+ * ```
399
+ *
400
+ * @param cmd - {@link CommandBuilder} to register as the default.
401
+ * @returns The builder (for chaining).
402
+ */
403
+ default(cmd) {
404
+ if (this.schema.defaultCommand !== void 0) throw new CLIError("Only one default command is allowed", {
405
+ code: "DUPLICATE_DEFAULT",
406
+ suggest: "Call .default() only once when building the CLI"
407
+ });
408
+ assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
409
+ if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
410
+ const erased = eraseCommand(cmd);
411
+ return new CLIBuilder({
412
+ ...this.schema,
413
+ defaultCommand: erased
414
+ });
415
+ }
416
+ /**
417
+ * Register a CLI plugin.
418
+ *
419
+ * Plugins run in registration order. At each lifecycle stage, all hooks for
420
+ * the first plugin run before hooks for the second plugin, and so on.
421
+ *
422
+ * @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
423
+ * @returns The builder (for chaining).
424
+ * @see {@link plugin} to construct plugin definitions.
425
+ */
426
+ plugin(definition) {
427
+ return new CLIBuilder({
428
+ ...this.schema,
429
+ plugins: [...this.schema.plugins, definition]
430
+ });
431
+ }
432
+ /**
433
+ * Register built-in shell completion.
434
+ *
435
+ * By default (`{ as: 'command' }`) this registers a `completions` subcommand
436
+ * that accepts a `shell` argument and writes the script to stdout. With
437
+ * `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
438
+ * the CLI root — no subcommand is registered, so a default command stays the
439
+ * lone root surface. The flag may be given without a value to auto-detect the
440
+ * shell from `$SHELL` / `$PSModulePath`.
441
+ *
442
+ * In subcommand mode, call this **after** registering all other commands so
443
+ * the completion script includes the full command set: that path snapshots the
444
+ * schema (and completion options) at call time, so commands registered
445
+ * afterwards will not appear in that subcommand's generated script. In flag
446
+ * mode, generation runs at execution time from the final builder schema, so
447
+ * registration order does not matter.
448
+ *
449
+ * @example
450
+ * ```ts
451
+ * // Subcommand form (default):
452
+ * cli('mycli')
453
+ * .version('1.0.0')
454
+ * .command(deploy)
455
+ * .completions({ rootMode: 'surface' })
456
+ * .run();
457
+ *
458
+ * // Eager-flag form, ideal for single-command CLIs:
459
+ * cli('mycli')
460
+ * .completions({ as: 'flag' })
461
+ * .default(serve)
462
+ * .run();
463
+ * ```
464
+ */
465
+ completions(options) {
466
+ if (this.schema.hasBuiltInCompletions) throw new CLIError(".completions() has already been called", {
467
+ code: "DUPLICATE_COMMAND",
468
+ suggest: "Call .completions() only once when building the CLI"
469
+ });
470
+ if (options?.as === "flag") {
471
+ if (this.schema.defaultCommand !== void 0) assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
472
+ for (const registered of this.schema.commands) assertNoCompletionsFlagCollision(registered.schema);
473
+ return new CLIBuilder({
474
+ ...this.schema,
475
+ hasBuiltInCompletions: true,
476
+ completionsFlag: {
477
+ shells: SHELLS,
478
+ options
479
+ }
480
+ });
481
+ }
482
+ const cliSchema = this.schema;
483
+ const completionOptions = options;
484
+ const cmd = command("completions").alias("completion").description("Generate shell completion script").arg("shell", arg.custom((raw) => {
485
+ const shell = normalizeShell(raw);
486
+ if (shell === void 0) throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(", ")}`);
487
+ return shell;
488
+ }).env("SHELL").describe(`Target shell (${SHELLS.join(", ")})`)).action(({ args, meta, out }) => {
489
+ const script = generateCompletion(meta.bin === cliSchema.name ? cliSchema : {
490
+ ...cliSchema,
491
+ name: meta.bin
492
+ }, args.shell, completionOptions);
493
+ if (out.jsonMode) out.json({
494
+ shell: args.shell,
495
+ script
496
+ });
497
+ else out.log(script);
498
+ });
499
+ return new CLIBuilder({
500
+ ...this.command(cmd).schema,
501
+ hasBuiltInCompletions: true
502
+ });
503
+ }
504
+ /**
505
+ * Execute the CLI program against explicit argv.
506
+ *
507
+ * This is the testable execution path — no process state is touched.
508
+ * Returns a structured {@linkcode RunResult} with exit code and captured output.
509
+ *
510
+ * @param argv - Raw argv tokens (NOT including the binary/script path,
511
+ * i.e. equivalent to `process.argv.slice(2)`).
512
+ * @param options - Injectable runtime state.
513
+ * @returns Structured result with exit code and captured output.
514
+ */
515
+ async execute(argv, options) {
516
+ const jsonMode = includesBeforeSeparator(argv, "--json") || options?.jsonMode === true;
517
+ const captureOptions = {
518
+ ...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
519
+ ...jsonMode ? { jsonMode } : {},
520
+ ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {}
521
+ };
522
+ let out;
523
+ let captured;
524
+ if (options?.out !== void 0) {
525
+ out = options.out;
526
+ captured = options.captured ?? {
527
+ stdout: [],
528
+ stderr: [],
529
+ activity: []
530
+ };
531
+ } else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
532
+ clearRequestedExitCode(out);
533
+ const helpOptions = {
534
+ ...this.schema.helpConfig,
535
+ ...options?.help,
536
+ binName: options?.help?.binName ?? this.schema.name,
537
+ hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isTTY
538
+ };
539
+ const effectiveOptions = {
540
+ ...options,
541
+ plugins: this.schema.plugins,
542
+ ...jsonMode ? { jsonMode } : {}
543
+ };
544
+ const output = {
545
+ jsonMode,
546
+ isTTY: out.isTTY,
547
+ verbosity: options?.verbosity ?? "normal"
548
+ };
549
+ const planned = planInvocation({
550
+ schema: this.schema,
551
+ argv,
552
+ help: helpOptions,
553
+ output
554
+ });
555
+ switch (planned.kind) {
556
+ case "root-version":
557
+ out.log(planned.version);
558
+ return buildRunResult({
559
+ exitCode: 0,
560
+ error: void 0
561
+ }, captured);
562
+ case "root-completions": {
563
+ const shell = planned.shell ?? detectShell(options?.env ?? {});
564
+ if (shell === void 0) {
565
+ const error = new CLIError("Could not detect shell", {
566
+ code: "MISSING_VALUE",
567
+ suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`
568
+ });
569
+ if (jsonMode) out.json({ error: error.toJSON() });
570
+ else {
571
+ out.error(error.message);
572
+ out.error(`Suggestion: ${error.suggest}`);
573
+ }
574
+ return buildRunResult({
575
+ exitCode: error.exitCode,
576
+ error
577
+ }, captured);
578
+ }
579
+ const script = generateCompletion(helpOptions.binName === void 0 || helpOptions.binName === this.schema.name ? this.schema : {
580
+ ...this.schema,
581
+ name: helpOptions.binName
582
+ }, shell, planned.options);
583
+ if (jsonMode) out.json({
584
+ shell,
585
+ script
586
+ });
587
+ else out.log(script);
588
+ return buildRunResult({
589
+ exitCode: 0,
590
+ error: void 0
591
+ }, captured);
592
+ }
593
+ case "root-help": {
594
+ const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
595
+ out.log(helpText);
596
+ return buildRunResult({
597
+ exitCode: 0,
598
+ error: void 0
599
+ }, captured);
600
+ }
601
+ case "dispatch-error":
602
+ if (jsonMode) out.json({ error: planned.error.toJSON() });
603
+ else {
604
+ out.error(planned.error.message);
605
+ if (planned.error.suggest !== void 0 && planned.error.code !== "NO_ACTION") out.error(`Suggestion: ${planned.error.suggest}`);
606
+ }
607
+ return buildRunResult({
608
+ exitCode: planned.error.exitCode,
609
+ error: planned.error
610
+ }, captured);
611
+ case "needs-subcommand": {
612
+ const helpText = formatHelp(planned.command.schema, planned.help);
613
+ out.log(helpText);
614
+ return buildRunResult({
615
+ exitCode: 0,
616
+ error: void 0
617
+ }, captured);
618
+ }
619
+ case "match": {
620
+ const commandRunOptions = buildCommandRunOptions(effectiveOptions, planned.plan.help ?? helpOptions, planned.plan.meta);
621
+ if (planned.plan.command._command === void 0) return planned.plan.command._execute(planned.plan.argv, {
622
+ ...commandRunOptions,
623
+ mergedSchema: planned.plan.mergedSchema
624
+ });
625
+ return buildRunResult(await executeCommand({
626
+ command: planned.plan.command._command,
627
+ argv: planned.plan.argv,
628
+ out,
629
+ schema: planned.plan.mergedSchema,
630
+ meta: planned.plan.meta,
631
+ options: commandRunOptions
632
+ }), captured);
633
+ }
634
+ }
635
+ }
636
+ /**
637
+ * Run the CLI program as a production entry point.
638
+ *
639
+ * Reads argv from the runtime adapter, dispatches to the matched
640
+ * command, writes output to real streams, and exits the process.
641
+ *
642
+ * This is the **only** place that touches process state (via the
643
+ * adapter). For testing, use `.execute()` instead — or provide a
644
+ * test adapter via `options.adapter`.
645
+ *
646
+ * Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
647
+ * which auto-detects the runtime (Node.js, Bun) and creates
648
+ * the appropriate adapter.
649
+ *
650
+ * @param options - Optional runtime configuration including adapter.
651
+ */
652
+ async run(options) {
653
+ const adapter = options?.adapter ?? createAdapter();
654
+ const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : void 0;
655
+ const preflight = await prepareRuntimePreflight({
656
+ schema: this.schema,
657
+ adapter,
658
+ options,
659
+ inheritedName
660
+ });
661
+ if (preflight.kind === "config-error") {
662
+ if (preflight.jsonMode) adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
663
+ else {
664
+ adapter.stderr(`Error: ${preflight.error.message}\n`);
665
+ if (preflight.error.suggest !== void 0) adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
666
+ }
667
+ return adapter.exit(preflight.error.exitCode);
668
+ }
669
+ const effectiveBuilder = preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
670
+ const executeOptions = {
671
+ ...options,
672
+ ...preflight.inputs,
673
+ out: createOutput({
674
+ stdout: adapter.stdout,
675
+ stderr: adapter.stderr,
676
+ jsonMode: preflight.inputs.jsonMode,
677
+ isTTY: preflight.inputs.isTTY,
678
+ ...preflight.inputs.verbosity !== "normal" ? { verbosity: preflight.inputs.verbosity } : {}
679
+ })
680
+ };
681
+ const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
682
+ for (const line of result.stdout) adapter.stdout(line);
683
+ for (const line of result.stderr) adapter.stderr(line);
684
+ return adapter.exit(result.exitCode);
685
+ }
686
+ };
687
+ const RUNTIME_BINARIES = /* @__PURE__ */ new Set([
688
+ "bun",
689
+ "deno",
690
+ "node",
691
+ "tsx"
692
+ ]);
693
+ /**
694
+ * Extract the final path segment from a path-like or URL-like string.
695
+ *
696
+ * @param input - Forward- or backslash-delimited path.
697
+ * @returns Trailing segment, or `undefined` when the input is empty or slash-only.
698
+ *
699
+ * @internal
700
+ */
701
+ function basename(input) {
702
+ const trimmed = stripTrailing(input, [47, 92]);
703
+ if (trimmed.length === 0) return void 0;
704
+ const slashIdx = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
705
+ const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
706
+ return name.length > 0 ? name : void 0;
707
+ }
708
+ /**
709
+ * Detect known interpreter/runtime binary names (node, bun, deno, tsx).
710
+ *
711
+ * @param input - Candidate binary name, with or without `.exe` suffix.
712
+ * @returns `true` when `input` matches a known runtime after normalization.
713
+ *
714
+ * @internal
715
+ */
716
+ function isRuntimeBinaryName(input) {
717
+ const normalized = input.toLowerCase().replace(/\.exe$/i, "");
718
+ return RUNTIME_BINARIES.has(normalized);
719
+ }
720
+ /**
721
+ * Infer the displayed CLI name from the current runtime invocation.
722
+ *
723
+ * Resolution order:
724
+ * 1. Node/Bun/tsx-style interpreters → script/entry argument basename
725
+ * 2. Standalone executable invocations → argv[0] basename
726
+ * 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
727
+ *
728
+ * @param argv - Full process argv (typically `process.argv` or adapter equivalent).
729
+ * @returns Inferred program name, or `undefined` when inference is ambiguous.
730
+ *
731
+ * @internal
732
+ */
733
+ function inferInvocationName(argv) {
734
+ const argv0 = argv[0];
735
+ const argv1 = argv[1];
736
+ const runtimeName = argv0 !== void 0 ? basename(argv0) : void 0;
737
+ if (runtimeName !== void 0 && isRuntimeBinaryName(runtimeName)) {
738
+ if (runtimeName === "bun" && argv1 === "run") {
739
+ const entryArg = argv[2];
740
+ if (entryArg === void 0 || entryArg.startsWith("-")) return void 0;
741
+ return basename(entryArg);
742
+ }
743
+ if (runtimeName === "deno" && argv1 === "run") return void 0;
744
+ if (argv1 === void 0 || argv1.startsWith("-")) return void 0;
745
+ return basename(argv1);
746
+ }
747
+ return argv0 !== void 0 ? basename(argv0) : void 0;
748
+ }
749
+ /** Coerce a `string | URL` link input to its string form. @internal */
750
+ function toUrlString(value) {
751
+ if (value === void 0) return void 0;
752
+ return value instanceof URL ? value.href : value;
753
+ }
754
+ /**
755
+ * Resolve derived help links against pre-loaded package.json data.
756
+ *
757
+ * `.run()` resolves links during runtime preflight (where discovered
758
+ * package.json metadata lives); this covers the filesystem-free
759
+ * `.execute()` path, where only the `.packageJson(data)` overload can
760
+ * contribute. Idempotent — already-resolved fields pass through unchanged.
761
+ *
762
+ * @internal
763
+ */
764
+ function resolveHelpLinksSchema(schema) {
765
+ if (schema.helpLinks === void 0) return schema;
766
+ return {
767
+ ...schema,
768
+ helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version)
769
+ };
770
+ }
771
+ /** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
772
+ const DEFAULT_MANIFEST_FILES = ["package.json"];
773
+ /** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
774
+ const DENO_MANIFEST_FILES = [
775
+ "deno.json",
776
+ "deno.jsonc",
777
+ "jsr.json"
778
+ ];
779
+ /**
780
+ * Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
781
+ * pair stored in {@link ResolvedManifestSettings}.
782
+ *
783
+ * @internal
784
+ */
785
+ function normalizeInferName(option) {
786
+ if (option === void 0 || option === false) return {
787
+ inferName: false,
788
+ stripScope: true
789
+ };
790
+ if (option === true) return {
791
+ inferName: true,
792
+ stripScope: true
793
+ };
794
+ return {
795
+ inferName: true,
796
+ stripScope: option.scope !== "keep"
797
+ };
798
+ }
799
+ /**
800
+ * Build the next {@link CLISchema} for a manifest builder method.
801
+ *
802
+ * Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
803
+ * {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
804
+ * merges `version`/`description` immediately so `.execute()` sees them; the
805
+ * settings overload stores discovery config for runtime preflight.
806
+ *
807
+ * @internal
808
+ */
809
+ function buildManifestSchema(schema, input, defaultFiles, pinFiles) {
810
+ if (isPackageJsonData(input)) return {
811
+ ...schema,
812
+ ...schema.version === void 0 && input.version !== void 0 ? { version: input.version } : {},
813
+ ...schema.description === void 0 && input.description !== void 0 ? { description: input.description } : {},
814
+ packageJsonSettings: {
815
+ inferName: false,
816
+ stripScope: true,
817
+ from: void 0,
818
+ files: defaultFiles,
819
+ data: input
820
+ }
821
+ };
822
+ const { inferName, stripScope } = normalizeInferName(input?.inferName);
823
+ const files = pinFiles ? defaultFiles : input?.files ?? defaultFiles;
824
+ return {
825
+ ...schema,
826
+ packageJsonSettings: {
827
+ inferName,
828
+ stripScope,
829
+ from: normalizeFromSetting(input?.from),
830
+ files,
831
+ data: void 0
832
+ }
833
+ };
834
+ }
835
+ /**
836
+ * Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
837
+ * (string path, `file:` URL string, or {@link URL} instance) to a plain
838
+ * filesystem path string. `undefined` passes through unchanged.
839
+ *
840
+ * Runtime-agnostic by design — relies only on the `URL` global (available in
841
+ * every JS runtime) rather than `node:url`, keeping core free of Node
842
+ * built-ins. Non-`file:` inputs are returned unchanged as paths.
843
+ *
844
+ * @internal
845
+ */
846
+ function normalizeFromSetting(from) {
847
+ if (from === void 0) return void 0;
848
+ if (from instanceof URL) {
849
+ if (from.protocol !== "file:") return from.href;
850
+ } else if (!from.startsWith("file:")) return from;
851
+ const decoded = decodeURIComponent(new URL(from).pathname);
852
+ if (/^\/[A-Za-z]:/.test(decoded)) return decoded.slice(1).replace(/\//g, "\\");
853
+ return decoded;
854
+ }
855
+ /**
856
+ * Predicate distinguishing the {@link PackageJsonData | data} overload of
857
+ * `.packageJson()` from the settings overload at runtime.
858
+ *
859
+ * A value is treated as `PackageJsonData` when it's a plain object that
860
+ * carries at least one recognised field (`name`, `version`, `description`,
861
+ * `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
862
+ * object (`inferName` / `from`) falls through to the settings overload.
863
+ *
864
+ * npm's `files` field (publish globs) is intentionally NOT recognised here, so
865
+ * an object whose only key is `files` routes to the settings overload — where
866
+ * `files` means candidate manifest filenames, never publish globs. Manifests
867
+ * that publish a CLI carry `name`/`version`, so those route to the data overload
868
+ * as expected.
869
+ *
870
+ * Edge case: a metadata-less manifest (e.g. a versionless private-root
871
+ * `package.json` carrying only `files`/`private`) routes to settings, so its
872
+ * `files` would be read as candidate filenames and the object is not stored as
873
+ * data. This is harmless in practice — a metadata-less manifest contributes no
874
+ * `version`/`description` either way — but it means a pre-loaded object must
875
+ * carry real metadata to be honoured as data.
876
+ *
877
+ * @internal
878
+ */
879
+ function isPackageJsonData(value) {
880
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
881
+ return "name" in value || "version" in value || "description" in value || "bin" in value || "homepage" in value || "repository" in value;
882
+ }
883
+ function cli(nameOrOptions) {
884
+ return new CLIBuilder({
885
+ name: typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions.name ?? "cli",
886
+ inheritName: typeof nameOrOptions === "string" ? false : nameOrOptions.inherit ?? false,
887
+ version: void 0,
888
+ description: void 0,
889
+ commands: [],
890
+ defaultCommand: void 0,
891
+ configSettings: void 0,
892
+ packageJsonSettings: void 0,
893
+ helpLinks: void 0,
894
+ hasBuiltInCompletions: false,
895
+ completionsFlag: void 0,
896
+ helpConfig: void 0,
897
+ plugins: []
898
+ });
899
+ }
900
+ //#endregion
901
+ export { CLIBuilder, cli };