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

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