@kjanat/dreamcli 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/CHANGELOG.md +45 -6
  2. package/LICENSE +1 -1
  3. package/README.md +296 -164
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -920
  96. package/dist/index.mjs +1 -10
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +6 -252
  115. package/dist/runtime.mjs +1 -1
  116. package/dist/testkit.d.mts +5 -24
  117. package/dist/testkit.mjs +1 -1
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +2 -2
  122. package/examples/gh/package.json +7 -11
  123. package/examples/gh/src/commands/auth.ts +2 -2
  124. package/examples/gh/src/commands/issue.ts +4 -4
  125. package/examples/gh/src/commands/pr.ts +4 -4
  126. package/examples/gh/src/docs.ts +11 -0
  127. package/examples/gh/src/lib/auth.ts +1 -1
  128. package/examples/gh/src/main.test.ts +6 -5
  129. package/examples/gh/src/main.ts +8 -6
  130. package/examples/interactive.ts +3 -3
  131. package/examples/json-mode.ts +4 -6
  132. package/examples/middleware.ts +3 -3
  133. package/examples/multi-command.ts +3 -3
  134. package/examples/spinner-progress.ts +5 -5
  135. package/examples/testing.ts +8 -6
  136. package/package.json +70 -44
  137. package/src/core/cli/dispatch.ts +4 -0
  138. package/src/core/cli/index.ts +185 -632
  139. package/src/core/cli/planner.ts +413 -0
  140. package/src/core/cli/plugin.ts +7 -1
  141. package/src/core/cli/propagate.ts +1 -1
  142. package/src/core/cli/runtime-preflight.ts +409 -0
  143. package/src/core/completion/index.ts +15 -9
  144. package/src/core/completion/shells/bash.ts +6 -3
  145. package/src/core/completion/shells/fish.ts +245 -10
  146. package/src/core/completion/shells/powershell.ts +390 -9
  147. package/src/core/completion/shells/shared.ts +4 -4
  148. package/src/core/completion/shells/zsh.ts +12 -7
  149. package/src/core/config/index.ts +7 -4
  150. package/src/core/config/package-json.ts +6 -2
  151. package/src/core/errors/index.ts +23 -8
  152. package/src/core/execution/index.ts +270 -0
  153. package/src/core/help/index.ts +13 -15
  154. package/src/core/json-schema/index.ts +193 -7
  155. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  156. package/src/core/output/contracts.ts +194 -0
  157. package/src/core/output/index.ts +47 -82
  158. package/src/core/output/renderers.ts +125 -0
  159. package/src/core/parse/index.ts +39 -21
  160. package/src/core/prompt/index.ts +44 -27
  161. package/src/core/resolve/args.ts +144 -0
  162. package/src/core/resolve/coerce.ts +432 -0
  163. package/src/core/resolve/config.ts +26 -0
  164. package/src/core/resolve/contracts.ts +135 -0
  165. package/src/core/resolve/errors.ts +227 -0
  166. package/src/core/resolve/flags.ts +205 -0
  167. package/src/core/resolve/index.ts +41 -1264
  168. package/src/core/resolve/property.ts +99 -0
  169. package/src/core/schema/activity.ts +3 -0
  170. package/src/core/schema/arg.ts +26 -14
  171. package/src/core/schema/command.ts +265 -38
  172. package/src/core/schema/flag.ts +120 -15
  173. package/src/core/schema/index.ts +11 -2
  174. package/src/core/schema/middleware.ts +6 -6
  175. package/src/core/schema/prompt.ts +9 -1
  176. package/src/core/schema/run.ts +25 -17
  177. package/src/core/schema-dsl/index.ts +109 -0
  178. package/src/core/schema-dsl/parse.ts +262 -0
  179. package/src/core/schema-dsl/runtime.ts +609 -0
  180. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  181. package/src/core/testkit/index.ts +55 -297
  182. package/src/index.ts +10 -4
  183. package/src/runtime/adapter.ts +13 -10
  184. package/src/runtime/auto.ts +3 -3
  185. package/src/runtime/bun.ts +4 -4
  186. package/src/runtime/deno.ts +43 -29
  187. package/src/runtime/detect.ts +4 -1
  188. package/src/runtime/index.ts +1 -1
  189. package/src/runtime/node.ts +43 -21
  190. package/src/runtime/paths.ts +9 -3
  191. package/src/runtime/support.ts +20 -4
  192. package/src/runtime.ts +1 -1
  193. package/src/testkit.ts +10 -8
  194. package/dist/adapter-CCSh5juX.cjs +0 -1
  195. package/dist/adapter-DIwO-q7K.d.mts +0 -3447
  196. package/dist/adapter-DQnxxLiE.d.cts +0 -3447
  197. package/dist/auto-5cjZaF9V.mjs +0 -3
  198. package/dist/auto-B0eSgoDw.cjs +0 -3
  199. package/dist/index.cjs +0 -10
  200. package/dist/index.d.cts +0 -920
  201. package/dist/runtime.cjs +0 -1
  202. package/dist/runtime.d.cts +0 -253
  203. package/dist/testkit-CEDYPvhF.mjs +0 -14
  204. package/dist/testkit-ClIKijxC.cjs +0 -14
  205. package/dist/testkit.cjs +0 -1
  206. package/dist/testkit.d.cts +0 -25
  207. package/examples/gh/tsconfig.json +0 -37
  208. package/examples/tsconfig.json +0 -17
  209. package/src/core/cli/AGENTS.md +0 -72
  210. package/src/core/completion/AGENTS.md +0 -72
  211. package/src/core/completion/completion-test-helpers.ts +0 -48
  212. package/src/core/output/AGENTS.md +0 -69
  213. package/src/core/resolve/AGENTS.md +0 -69
  214. package/src/core/schema/AGENTS.md +0 -61
  215. package/src/core/testkit/AGENTS.md +0 -55
  216. package/src/runtime/AGENTS.md +0 -74
  217. package/src/runtime/test-helpers.ts +0 -40
package/dist/index.mjs CHANGED
@@ -1,10 +1 @@
1
- import{_ as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,s as f,t as p,u as m,v as h}from"./testkit-CEDYPvhF.mjs";import{t as g}from"./auto-5cjZaF9V.mjs";function _(e){if(e.length<=1)return{};let t={};for(let n=0;n<e.length-1;n++){let r=e[n];if(r!==void 0){for(let[i,a]of Object.entries(r.flags))if(a.propagate){let r=!1;for(let t=n+1;t<e.length-1;t++){let n=e[t];if(n!==void 0&&i in n.flags){r=!0;break}}r||(t[i]=a)}}}let n=e[e.length-1];if(n!==void 0)for(let e of Object.keys(n.flags))delete t[e];return t}function v(e){let t=e.commands.map(e=>e.schema).filter(e=>!e.hidden),n=e.defaultCommand?.schema,r=n!==void 0&&!n.hidden?n:void 0;return{visibleCommands:t,visibleDefaultCommand:r,hasSingleVisibleDefault:r!==void 0&&t.length===1&&t[0]?.name===r.name,hasVisibleSiblingCommands:r!==void 0&&t.some(e=>e.name!==r.name)}}function y(){return`dreamcli v1.0.0 (e399212)`}function b(e,t=`subcommands`){let n=v(e),r=ee(e.version!==void 0),i=n.visibleDefaultCommand?.flags??{},a=t===`surface`?n.visibleDefaultCommand!==void 0:n.hasSingleVisibleDefault;return{visibleCommands:n.visibleCommands,visibleDefaultCommand:n.visibleDefaultCommand,rootFlags:r,defaultFlags:i,includeDefaultFlags:a}}function ee(e){return{help:te(`Show help text`),...e?{version:te(`Show version`)}:{}}}function te(e){return{kind:`boolean`,presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:e,enumValues:void 0,elementSchema:void 0,prompt:void 0,parseFn:void 0,deprecated:void 0,propagate:!1}}function x(e,t=[]){let n=[];for(let r of e){if(r.hidden)continue;let e=[...t,r],i=_(e),a={...i,...r.flags},o=r.commands.filter(e=>!e.hidden);n.push({path:e.map(e=>e.name),schema:r,propagatedFlags:i,mergedFlags:a,children:o}),o.length>0&&n.push(...x(o,e))}return n}function S(e){let t=e.replace(/[^a-zA-Z0-9_]/g,`_`);if(t===e)return t;let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return`${t}_${(n>>>0).toString(16).padStart(8,`0`)}`}function C(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function w(e,t){let n=`_${S(t?.functionPrefix??e.name)}_completions`,r=b(e,t?.rootMode),i=r.visibleCommands,a=x(i),o=a.reduce((e,t)=>Math.max(e,t.path.length),0),s=[];if(s.push(`#!/usr/bin/env bash`),s.push(`# Bash completion for ${e.name}`),s.push(`# Generated by ${y()}`),s.push(`#`),s.push(`# Usage: source <(${e.name} completions bash)`),s.push(`#`),s.push(`# Install permanently:`),s.push(`# ${e.name} completions bash > /etc/bash_completion.d/${e.name} # Linux`),s.push(`# ${e.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${e.name} # macOS`),s.push(`#`),s.push(`# Requires: bash-completion (provides _init_completion)`),s.push(``),s.push(`${n}() {`),s.push(` local cur prev words cword`),s.push(` _init_completion || return`),s.push(``),i.length>0){let e=a.filter(e=>e.children.length>0),t=oe(a,r);s.push(` # Build subcommand path by scanning COMP_WORDS`),s.push(` local subcmd_path=""`),s.push(` local i`),s.push(` for ((i = 1; i < cword; i++)); do`),s.push(' case "${words[i]}" in'),s.push(` --) break ;;`),t.length>0&&s.push(`\t\t\t${t}) ((i++)); continue ;;`),s.push(` -*) continue ;;`),s.push(` esac`),ne(s,i,e,o),s.push(` done`),s.push(``),s.push(` # Complete flags and subcommands for the active path`),s.push(` case "$subcmd_path" in`);for(let e of a){let t=e.path.join(` `),n=e.mergedFlags,r=ce(n),i=O(n),a=se(e.children.flatMap(e=>[e.name,...e.aliases])).map(D).join(` `),o=i.split(` `).filter(Boolean).map(D).join(` `),c=a.length>0?`${a} ${o}`:o;if(s.push(`\t\t${re(t)})`),r.length>0){s.push(` local enum_flag=""`),s.push(` local enum_cur="$cur"`),s.push(` local enum_prefix=""`),s.push(` if [[ "$cur" == --*=* ]]; then`),s.push(' enum_flag="${cur%%=*}"'),s.push(' enum_cur="${cur#*=}"'),s.push(' enum_prefix="${cur%%=*}="'),s.push(` fi`),s.push(' case "${enum_flag:-$prev}" in');for(let e of r)s.push(`\t\t\t\t${e.flags})`),s.push(ie(e.values,` `,`enum_cur`,`enum_prefix`)),s.push(` return`),s.push(` ;;`);s.push(` *)`),s.push(` ;;`),s.push(` esac`)}s.push(`\t\t\tCOMPREPLY=($(compgen -W '${c.trim()}' -- "$cur"))`),s.push(` return`),s.push(` ;;`)}s.push(` *)`),s.push(` ;;`),s.push(` esac`),s.push(``);let n=O(r.rootFlags).split(` `).filter(Boolean),c=r.includeDefaultFlags?O(r.defaultFlags).split(` `).filter(Boolean):[],l=se([...i.flatMap(e=>[e.name,...e.aliases]),...n,...c]).map(D).join(` `);s.push(` # Root-level completions: visible root surface`),s.push(`\tCOMPREPLY=($(compgen -W '${l}' -- "$cur"))`)}else{let e=O(r.rootFlags);s.push(`\tCOMPREPLY=($(compgen -W '${e}' -- "$cur"))`)}return s.push(`}`),s.push(``),s.push(`complete -F ${n} ${C(e.name)}`),s.push(``),s.join(`
2
- `)}function ne(e,t,n,r){e.push(` case "$subcmd_path" in`),e.push(` '')`),e.push(' case "${words[i]}" in');for(let n of t){let t=[n.name,...n.aliases].map(T);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="${E(n.name)}"`),e.push(` ;;`)}if(e.push(` esac`),e.push(` ;;`),r>1)for(let t of n){let n=t.path.join(` `);e.push(`\t\t\t${re(n)})`),e.push(' case "${words[i]}" in');for(let n of t.children){let t=[n.name,...n.aliases].map(T);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="$subcmd_path ${E(n.name)}"`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`)}e.push(` esac`)}function re(e){return e.includes(` `)?`"${E(e)}"`:T(e)}function T(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function E(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\$/g,`\\$`).replace(/`/g,"\\`")}function D(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/'/g,`'\\''`)}function ie(e,t,n=`cur`,r){let i=[];if(e.some(e=>!/^[a-zA-Z0-9_\-.]+$/.test(e))){let r=e.map(ae).join(`\\n`);i.push(`${t}local IFS=$'\\n'`),i.push(`${t}COMPREPLY=($(compgen -W $'${r}' -- "$${n}"))`)}else i.push(`${t}COMPREPLY=($(compgen -W '${e.join(` `)}' -- "$${n}"))`);return r!==void 0&&(i.push(`${t}if [[ -n "$${r}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`),i.push(`${t}\tlocal i`),i.push(`${t}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`),i.push(`${t}\t\tCOMPREPLY[i]="$${r}\${COMPREPLY[i]}"`),i.push(`${t}\tdone`),i.push(`${t}fi`)),i.join(`
3
- `)}function ae(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}function O(e){let t=[];for(let[n,r]of Object.entries(e)){t.push(`--${n}`);for(let e of r.aliases)t.push(e.length===1?`-${e}`:`--${e}`)}return t.join(` `)}function oe(e,t){let n=new Set,r=e=>{for(let[t,r]of Object.entries(e))if(r.kind!==`boolean`){n.add(`--${t}`);for(let e of r.aliases)n.add(e.length===1?`-${e}`:`--${e}`)}};for(let t of e)r(t.mergedFlags);return r(t.rootFlags),t.includeDefaultFlags&&r(t.defaultFlags),[...n].map(T).join(`|`)}function se(e){return[...new Set(e)]}function ce(e){let t=[];for(let[n,r]of Object.entries(e)){if(r.kind!==`enum`||r.enumValues===void 0)continue;let e=[`--${n}`,...r.aliases.map(e=>e.length===1?`-${e}`:`--${e}`)].map(T);t.push({flags:e.join(`|`),values:r.enumValues})}return t}function le(e,t){throw new d(`Shell completion for 'fish' is not yet supported`,{code:`UNSUPPORTED_OPERATION`,suggest:`Supported shells: bash, zsh`})}function ue(e,t){throw new d(`Shell completion for 'powershell' is not yet supported`,{code:`UNSUPPORTED_OPERATION`,suggest:`Supported shells: bash, zsh`})}function de(e,t){let n=`_${S(t?.functionPrefix??e.name)}`,r=b(e,t?.rootMode),i=r.visibleCommands,a=x(i),o=[];o.push(`#compdef ${C(e.name)}`),o.push(`# Zsh completion for ${e.name}`),o.push(`# Generated by ${y()}`),o.push(`#`),o.push(`# Usage: source <(${e.name} completions zsh)`),o.push(`#`),o.push(`# Install permanently:`),o.push(`# ${e.name} completions zsh > "\${fpath[1]}/_${e.name}"`),o.push(`# # Then restart your shell`),o.push(``);let s=a.filter(e=>e.children.length>0),c=a.filter(e=>e.children.length===0);for(let e of c)e.path.length<2||pe(o,`${n}_${e.path.map(S).join(`_`)}`,e);let l=[...s].sort((e,t)=>t.path.length-e.path.length);for(let e of l)fe(o,`${n}_${e.path.map(S).join(`_`)}`,n,e);if(o.push(`${n}() {`),i.length>0){o.push(` local -a subcmds`),o.push(` local line state`),o.push(``);let e=A({...r.rootFlags,...r.includeDefaultFlags?r.defaultFlags:{}});o.push(` _arguments -C \\`);for(let t of e)o.push(`\t\t${t} \\`);o.push(` '1: :->subcmd' \\`),o.push(` '*::arg:->args'`),o.push(``),o.push(` case "$state" in`),o.push(` subcmd)`),o.push(` subcmds=(`),me(o,i,` `),o.push(` )`),o.push(` _describe 'command' subcmds`),o.push(` ;;`),o.push(` args)`),o.push(` case "$line[1]" in`);for(let e of i){let t=[e.name,...e.aliases].map(k),r=e.commands.filter(e=>!e.hidden);if(o.push(`\t\t\t\t${t.join(`|`)})`),r.length>0){let t=`${n}_${S(e.name)}`;o.push(`\t\t\t\t\t${t}`)}else{let t=a.find(t=>t.path.length===1&&t.schema.name===e.name);if(t===void 0)throw new d(`Missing completion node for command '${e.name}'`,{code:`UNEXPECTED_ERROR`});let n=A(t.mergedFlags);if(n.length>0){o.push(` _arguments \\`);for(let e=0;e<n.length;e++){let t=e<n.length-1?` \\`:``;o.push(`\t\t\t\t\t\t${n[e]}${t}`)}}}o.push(` ;;`)}o.push(` esac`),o.push(` ;;`),o.push(` esac`)}else{let e=A(r.rootFlags);o.push(` _arguments \\`);for(let t=0;t<e.length;t++){let n=t<e.length-1?` \\`:``;o.push(`\t\t${e[t]}${n}`)}}return o.push(`}`),o.push(``),o.push(`${n} "$@"`),o.push(``),o.join(`
4
- `)}function fe(e,t,n,r){e.push(`${t}() {`),e.push(` local -a subcmds`),e.push(` local line state`),e.push(``);let i=A(r.mergedFlags);e.push(` _arguments -C \\`);for(let t of i)e.push(`\t\t${t} \\`);e.push(` '1: :->subcmd' \\`),e.push(` '*::arg:->args'`),e.push(``),e.push(` case "$state" in`),e.push(` subcmd)`),e.push(` subcmds=(`),me(e,r.children,` `),e.push(` )`),e.push(` _describe 'command' subcmds`),e.push(` ;;`),e.push(` args)`),e.push(` case "$line[1]" in`);for(let t of r.children){let i=[t.name,...t.aliases].map(k),a=`${n}_${[...r.path,t.name].map(S).join(`_`)}`;e.push(`\t\t\t\t${i.join(`|`)})`),e.push(`\t\t\t\t\t${a}`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`),e.push(` esac`),e.push(`}`),e.push(``)}function pe(e,t,n){let r=A(n.mergedFlags);if(e.push(`${t}() {`),r.length>0){e.push(` _arguments \\`);for(let t=0;t<r.length;t++){let n=t<r.length-1?` \\`:``;e.push(`\t\t${r[t]}${n}`)}}e.push(`}`),e.push(``)}function me(e,t,n){for(let r of t){let t=r.description??r.name;for(let i of[r.name,...r.aliases])e.push(`${n}${C(`${i}:${t}`)}`)}}function k(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function he(e){return e.replace(/\\/g,`\\\\`).replace(/\]/g,`\\]`)}function A(e){let t=[];for(let[n,r]of Object.entries(e)){let e=he(r.description??n),i=`--${n}`,a=r.aliases.filter(e=>e.length===1).map(e=>`-${e}`),o=``;if(r.kind===`boolean`||(o=r.kind===`enum`&&r.enumValues!==void 0?`:value:(${r.enumValues.map(ge).join(` `)})`:`:value:`),a.length>0){let n=[...a,i],r=n.map(k).join(`,`);t.push(`${C(`(${n.join(` `)})`)}{${r}}${C(`[${e}]${o}`)}`)}else t.push(C(`${i}[${e}]${o}`))}return t}function ge(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/ /g,`\\ `).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)}const j=Object.freeze([`bash`,`zsh`]);function M(e,t,n){switch(t){case`bash`:return w(e,n);case`zsh`:return de(e,n);case`fish`:return le(e,n);case`powershell`:return ue(e,n)}}function N(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _e(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function ve(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function ye(e){let t=e.cwd;for(;t!==void 0;){let n=null;try{n=await e.readFile(ve(t,`package.json`))}catch{}if(n!==null){let e=be(n);if(e!==null)return e}t=_e(t)}return null}function be(e){try{let t=JSON.parse(e);if(!N(t))return null;let n=typeof t.name==`string`?t.name:void 0,r=typeof t.version==`string`?t.version:void 0,i=typeof t.description==`string`?t.description:void 0,a=xe(t.bin);return{...n===void 0?{}:{name:n},...r===void 0?{}:{version:r},...i===void 0?{}:{description:i},...a===void 0?{}:{bin:a}}}catch{return null}}function xe(e){if(typeof e==`string`)return e;if(!N(e))return;let t={};for(let[n,r]of Object.entries(e)){if(typeof r!=`string`)return;t[n]=r}return t}function P(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}function Se(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const F={extensions:[`json`],parse:e=>{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Config must be a JSON object`);return t}};function I(e,...t){let n=e.includes(`\\`)?`\\`:`/`;return[e,...t].join(n)}function Ce(e){let t=e.lastIndexOf(`.`);return t<=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))?``:e.slice(t+1).toLowerCase()}function L(e,t,n,r){let i=we(r),a=[];for(let n of i)a.push(I(t,`.${e}.${n}`));for(let n of i)a.push(I(t,`${e}.config.${n}`));for(let t of i)a.push(I(n,e,`config.${t}`));return a}function we(e){let t=new Set,n=[];for(let e of F.extensions){let r=e.toLowerCase();t.has(r)||(t.add(r),n.push(r))}if(e!==void 0)for(let r of e)for(let e of r.extensions){let r=e.toLowerCase();t.has(r)||(t.add(r),n.push(r))}return n}function Te(e){let t=new Map;for(let e of F.extensions)t.set(e.toLowerCase(),F);if(e!==void 0)for(let n of e)for(let e of n.extensions)t.set(e.toLowerCase(),n);return t}async function Ee(e,t,n){let r=Te(n?.loaders),i=n?.configPath===void 0?n?.searchPaths??L(e,t.cwd,t.configDir,n?.loaders):[n.configPath];for(let e of i){let i=await t.readFile(e);if(i===null){if(n?.configPath!==void 0)throw new d(`Config file not found: ${e}`,{code:`CONFIG_NOT_FOUND`,details:{path:e},suggest:`Create the config file or remove the --config flag`});continue}let a=Ce(e),o=r.get(a);if(o===void 0)throw new d(`No loader registered for config format: .${a}`,{code:`CONFIG_UNKNOWN_FORMAT`,details:{path:e,extension:a},suggest:`Supported formats: ${[...r.keys()].join(`, `)}`});try{let t=o.parse(i);if(!Se(t))throw Error(`Config loader must return a plain object`);return{found:!0,path:e,data:t,format:a}}catch(t){throw new d(`Failed to parse config file: ${e}`,{code:`CONFIG_PARSE_ERROR`,cause:t,details:{path:e,format:a,message:t instanceof Error?t.message:String(t)},suggest:`Check the config file for syntax errors`})}}return{found:!1}}function De(e,t){return{extensions:e,parse:t}}function R(e,t){return{kind:e,presence:`required`,variadic:!1,stdinMode:!1,defaultValue:void 0,description:void 0,envVar:void 0,enumValues:void 0,parseFn:void 0,deprecated:void 0,...t}}var z=class e{schema;constructor(e){this.schema=e}required(){return new e({...this.schema,presence:`required`})}optional(){return new e({...this.schema,presence:`optional`})}default(t){return new e({...this.schema,presence:`defaulted`,defaultValue:t})}variadic(){return new e({...this.schema,variadic:!0})}stdin(){return new e({...this.schema,stdinMode:!0})}env(t){return new e({...this.schema,envVar:t})}describe(t){return new e({...this.schema,description:t})}deprecated(t){return new e({...this.schema,deprecated:t??!0})}};const Oe={string(){return new z(R(`string`))},number(){return new z(R(`number`))},enum(e){return new z(R(`enum`,{enumValues:e}))},custom(e){return new z(R(`custom`,{parseFn:e}))}};function ke(e,t,n){if(t.stdinMode&&t.variadic)throw new d(`Argument <${e}> cannot be both variadic and stdin-backed`,{code:`INVALID_BUILDER_STATE`,details:{arg:e,stdinMode:!0,variadic:!0},suggest:`Remove .stdin() or .variadic() from this argument`});if(!t.stdinMode)return;let r=n.find(e=>e.schema.stdinMode);if(r!==void 0)throw new d(`Only one stdin argument is allowed; <${r.name}> is already stdin-backed`,{code:`DUPLICATE_STDIN_ARG`,details:{arg:e,existingArg:r.name},suggest:`Keep .stdin() on a single argument per command`})}function Ae(e){return e}var je=class e{schema;handler;_subcommands;_executionSteps;constructor(e,t,n,r){this.schema=e,this.handler=t,this._subcommands=n??[],this._executionSteps=r??[]}interactive(t){let n=t;return new e({...this.schema,interactive:n},this.handler,this._subcommands,this._executionSteps)}derive(t){let n=t;return new e({...this.schema,hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`derive`,handler:n}])}middleware(t){return new e({...this.schema,middleware:[...this.schema.middleware,t._handler],hasAction:!1},void 0,this._subcommands,[...this._executionSteps,{kind:`middleware`,handler:t._handler}])}description(t){return new e({...this.schema,description:t},this.handler,this._subcommands,this._executionSteps)}alias(t){return new e({...this.schema,aliases:[...this.schema.aliases,t]},this.handler,this._subcommands,this._executionSteps)}hidden(){return new e({...this.schema,hidden:!0},this.handler,this._subcommands,this._executionSteps)}example(t,n){let r=n===void 0?{command:t}:{command:t,description:n};return new e({...this.schema,examples:[...this.schema.examples,r]},this.handler,this._subcommands,this._executionSteps)}flag(t,n){let r={...this.schema.flags,[t]:n.schema};return new e({...this.schema,flags:r,hasAction:!1},void 0,this._subcommands,this._executionSteps)}arg(t,n){ke(t,n.schema,this.schema.args);let r={name:t,schema:n.schema},i=[...this.schema.args,r];return new e({...this.schema,args:i,hasAction:!1},void 0,this._subcommands,this._executionSteps)}command(t){return new e({...this.schema,commands:[...this.schema.commands,t.schema]},this.handler,[...this._subcommands,Ae(t)],this._executionSteps)}action(t){return new e({...this.schema,hasAction:!0},t,this._subcommands,this._executionSteps)}};function B(e){return new je({name:e,description:void 0,aliases:[],hidden:!1,examples:[],flags:{},args:[],hasAction:!1,interactive:void 0,middleware:[],commands:[]})}function Me(e){return B(e)}function V(e,t,n=[]){let r=-1;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--`){t+1<e.length&&(r=t+1);break}if(n!==void 0&&!n.startsWith(`-`)){r=t;break}}if(r===-1)return{kind:`unknown`,input:``,candidates:U(t),parentPath:n};let i=e[r];if(i===void 0)return{kind:`unknown`,input:``,candidates:U(t),parentPath:n};let a=t.get(i);if(a===void 0)return{kind:`unknown`,input:i,candidates:U(t),parentPath:n};let o=[...e.slice(0,r),...e.slice(r+1)],s=[...n,a.schema];if(a.subcommands.size>0){let e=V(o,a.subcommands,s);switch(e.kind){case`match`:return e;case`unknown`:return e.input===``?a.schema.hasAction?{kind:`match`,command:a,commandPath:s,remainingArgv:o}:{kind:`needs-subcommand`,command:a,commandPath:s}:a.schema.hasAction?{kind:`match`,command:a,commandPath:s,remainingArgv:o}:e;case`needs-subcommand`:return e;default:return e}}return{kind:`match`,command:a,commandPath:s,remainingArgv:o}}function Ne(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint16Array(i),o=new Uint16Array(i);for(let e=0;e<=r;e++)a[e]=e;for(let i=1;i<=n;i++){o[0]=i;for(let n=1;n<=r;n++){let r=e.charAt(i-1)===t.charAt(n-1)?0:1,s=a[n]??0,c=o[n-1]??0,l=a[n-1]??0;o[n]=Math.min(s+1,c+1,l+r)}[a,o]=[o,a]}return a[r]??Math.max(n,r)}function H(e,t){let n,r=4;for(let i of t){let t=Ne(e,i.schema.name);t<r&&(r=t,n=i.schema.name);for(let t of i.schema.aliases){let a=Ne(e,t);a<r&&(r=a,n=i.schema.name)}}return r<=3?n:void 0}function U(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}function Pe(e,t){let n=Object.freeze({...e});return Object.freeze({hooks:n,name:t})}function W(e,t){let n=t?.width??80,i=v(e);if(i.hasSingleVisibleDefault){let a=i.visibleDefaultCommand;if(a!==void 0){let o=Fe(e,i.visibleCommands,i.visibleDefaultCommand,n),s=o.findIndex(e=>e.startsWith(`Usage: `)),c=[...r(a,{...t,binName:e.name,isDefaultHelp:!0})],l=c.shift();return s!==-1&&l!==void 0&&(o[s]=Re(o[s]??``,l)),a.description!==void 0&&e.description!==void 0&&a.description===e.description&&c.shift(),o.push(...c),`${o.join(`
5
-
6
- `)}\n`}}let a=Fe(e,i.visibleCommands,i.visibleDefaultCommand,n),o=Ie(i.visibleCommands,i.visibleDefaultCommand);return a.push(o.length>0?`Run '${e.name} ${o} --help' for more information.`:`Run '${e.name} --help' for more information.`),`${a.join(`
7
-
8
- `)}\n`}function Fe(e,t,n,r){let i=[],a=e.version===void 0?e.name:`${e.name} v${e.version}`;i.push(a),e.description!==void 0&&i.push(e.description);let o=Ie(t,n);return i.push(o.length>0?`Usage: ${e.name} ${o} [options]`:`Usage: ${e.name} [options]`),t.length>0&&i.push(Le(t,n?.name,r)),i}function Ie(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function Le(e,t,n){let r=[`Commands:`],i=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>i&&(i=r)}let a=2+i+2;for(let i of e){let e=ze(` ${i.name===t?`${i.name} (default)`:i.name}`,a),o=i.description??``;o.length===0?r.push(e.trimEnd()):r.push(`${e}${Be(o,n,a)}`)}return r.join(`
9
- `)}function Re(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}function ze(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function Be(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
10
- `)}function G(e){let t=new Map;for(let n of e._subcommands){let e=G(n);t.set(n.schema.name,e);for(let r of n.schema.aliases)t.set(r,e)}return{schema:e.schema,subcommands:t,_execute(t,n){return p(e,t,n)}}}function Ve(e){let t=e.findIndex(e=>e.startsWith(`--config=`));if(t!==-1){let n=e[t].slice(9),r=[...e.slice(0,t),...e.slice(t+1)];return{configPath:n.length>0?n:void 0,filteredArgv:r}}let n=e.indexOf(`--config`),r=n>=0?e[n+1]:void 0;return n===-1||r===void 0?{configPath:void 0,filteredArgv:e}:{configPath:r,filteredArgv:[...e.slice(0,n),...e.slice(n+2)]}}function He(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function Ue(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}}}function We(e){let t=new Map;for(let n of e){t.set(n.schema.name,n);for(let e of n.schema.aliases)t.set(e,n)}return t}function Ge(e,t){if(t.includes(`--help`)||t.includes(`-h`))return!1;try{let n=f(e,t);return e.args.some(({name:e,schema:t})=>{let r=n.args[e];return t.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof c)return!1;throw e}}function Ke(e,t){let n=t.includes(`--json`)?t.filter(e=>e!==`--json`):t;if(n.includes(`--version`)||n.includes(`-V`)||n.includes(`--help`)||n.includes(`-h`))return!1;let r=n[0];if(r===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))||r===void 0&&e.schema.defaultCommand===void 0||e.schema.commands.length===0)return!1;let i=V(n,We(e.schema.commands)),a=e.schema.defaultCommand;switch(i.kind){case`unknown`:return a!==void 0&&i.parentPath.length===0&&(i.input===``?void 0:H(i.input,i.candidates))===void 0?Ge(a.schema,n):!1;case`needs-subcommand`:return!1;case`match`:{let e=_(i.commandPath);return Ge(Object.keys(e).length>0?{...i.command.schema,flags:{...e,...i.command.schema.flags}}:i.command.schema,i.remainingArgv)}}}var qe=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})}config(t,n){return new e({...this.schema,configSettings:{appName:t,loaders:n}})}configLoader(t){if(this.schema.configSettings===void 0)throw new d(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new e({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(t){return new e({...this.schema,packageJsonSettings:{inferName:t?.inferName??!1}})}command(t){return new e({...this.schema,commands:[...this.schema.commands,G(t)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new d(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});if(this.schema.commands.some(e=>e.schema.name===t.schema.name))throw new d(`Command '${t.schema.name}' is already registered`,{code:`DUPLICATE_COMMAND`,suggest:`Use .default() instead of .command() to register the default command`});let n=G(t);return new e({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(t){return new e({...this.schema,plugins:[...this.schema.plugins,t]})}completions(e){if(this.schema.commands.some(e=>e.schema.name===`completions`))throw new d(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let t=this.schema,n=e,r=new Map;for(let e of j)r.set(e,e);let i=B(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,Oe.custom(e=>{let t=e.split(/[\\/]/),n=(t[t.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=r.get(n);if(i===void 0)throw Error(`Unknown shell '${n}'. Valid shells: ${j.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${j.join(`, `)})`)).action(({args:e,meta:r,out:i})=>{let a=M(r.bin===t.name?t:{...t,name:r.bin},e.shell,n);i.jsonMode?i.json({shell:e.shell,script:a}):i.log(a)});return this.command(i)}async execute(e,t){let r=e.includes(`--json`),i=r||t?.jsonMode===!0,a=r?e.filter(e=>e!==`--json`):e,o={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...i?{jsonMode:i}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},l,u;t?.out===void 0?[l,u]=s(Object.keys(o).length>0?o:void 0):(l=t.out,u=t.captured??{stdout:[],stderr:[],activity:[]});let f={...t?.help,binName:t?.help?.binName??this.schema.name};if(this.schema.version!==void 0&&(a.includes(`--version`)||a.includes(`-V`)))return l.log(this.schema.version),K(0,u,void 0);let p=a.length>0?a[0]:void 0;if(p===`--help`||p===`-h`){let e=W(this.schema,f);return l.log(e),K(0,u,void 0)}if(p===`help`&&!this.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let e=a.slice(1);if(e.length===0){let e=W(this.schema,f);return l.log(e),K(0,u,void 0)}return this.execute([...e,`--help`],i?{...t,jsonMode:i}:t)}if(p===void 0&&this.schema.defaultCommand===void 0){let e=W(this.schema,f);return l.log(e),K(0,u,void 0)}if(this.schema.commands.length===0){let e=new d(`No commands registered`,{code:`NO_ACTION`,suggest:`Add commands via .command() before calling .run()`});return i?l.json({error:e.toJSON()}):l.error(e.message),K(1,u,e)}let m=V(a,We(this.schema.commands)),h=this.schema.defaultCommand,g={...t,plugins:this.schema.plugins,...i?{jsonMode:i}:{}};switch(m.kind){case`unknown`:{if(h!==void 0&&m.parentPath.length===0&&(m.input===``?void 0:H(m.input,m.candidates))===void 0){let e=Ue(g,f,He(this.schema,f,h.schema.name));return h._execute(a,{...e})}if(m.input===``){let e=a.find(e=>e.startsWith(`-`));if(e!==void 0){let t=new c(`Unknown flag ${e}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${this.schema.name} --help' for available commands`});return i?l.json({error:t.toJSON()}):(l.error(t.message),l.error(`Suggestion: ${t.suggest}`)),K(2,u,t)}let t=W(this.schema,f);return l.log(t),K(0,u,void 0)}let e=H(m.input,m.candidates),t=m.parentPath.length>0?`${this.schema.name} ${m.parentPath.map(e=>e.name).join(` `)}`:this.schema.name,n=new c(`Unknown command: ${m.input}`,{code:`UNKNOWN_COMMAND`,suggest:e===void 0?`Run '${t} --help' for available commands`:`Did you mean '${e}'?`});return i?l.json({error:n.toJSON()}):(l.error(n.message),n.suggest!==void 0&&l.error(`Suggestion: ${n.suggest}`)),K(2,u,n)}case`needs-subcommand`:{let e=m.commandPath.slice(0,-1).map(e=>e.name),t=[this.schema.name,...e].join(` `),r={...f,binName:t},i=n(m.command.schema,r);return l.log(i),K(0,u,void 0)}case`match`:{let e=_(m.commandPath),t=Object.keys(e).length>0?{...m.command.schema,flags:{...e,...m.command.schema.flags}}:void 0,n=Ue(g,f,He(this.schema,f,m.command.schema.name));return m.command._execute(m.remainingArgv,{...n,...t===void 0?{}:{mergedSchema:t}})}}}async run(t){let n=t?.adapter??g(),r=this.schema.inheritName?Xe(n.argv):void 0,{configPath:i,filteredArgv:a}=Ve(n.argv.slice(2)),s=a.includes(`--json`)||t?.jsonMode===!0,c=a[0],l=((c===void 0?void 0:this.schema.commands.find(e=>e.schema.name===c||e.schema.aliases.includes(c)))?.schema.name??this.schema.defaultCommand?.schema.name)===`completions`,u;if(this.schema.configSettings!==void 0&&!l&&t?.config===void 0)try{let e=await Ee(this.schema.configSettings.appName,n,{...i===void 0?{}:{configPath:i},...this.schema.configSettings.loaders===void 0?{}:{loaders:this.schema.configSettings.loaders}});e.found&&(u=e.data)}catch(e){if(e instanceof d)return s?n.stdout(`${JSON.stringify({error:e.toJSON()})}\n`):(n.stderr(`Error: ${e.message}\n`),e.suggest!==void 0&&n.stderr(`Suggestion: ${e.suggest}\n`)),n.exit(e.exitCode);throw e}let f=this.schema.packageJsonSettings,p=f!==void 0&&!l?await(async()=>{let t=await ye(n);if(t===null)return this;let r=this.schema,i=f.inferName?P(t):void 0;return new e({...r,...r.version===void 0&&t.version!==void 0?{version:t.version}:{},...r.description===void 0&&t.description!==void 0?{description:t.description}:{},...i===void 0?{}:{name:i}})})():this,h=r===void 0?p:new e({...p.schema,name:r}),_=t?.prompter===void 0&&n.stdinIsTTY?o(n.stdin,n.stderr):void 0,v=t?.stdinData===void 0&&Ke(h,a)?await n.readStdin():void 0,y={...t,...t?.env===void 0?{env:n.env}:{},...t?.isTTY===void 0?{isTTY:n.isTTY}:{},...v===void 0?{}:{stdinData:v},..._===void 0?{}:{prompter:_},...u===void 0?{}:{config:u},out:m({stdout:n.stdout,stderr:n.stderr,jsonMode:s,isTTY:t?.isTTY??n.isTTY,...t?.verbosity===void 0?{}:{verbosity:t.verbosity}})},b=await h.execute(a,y);for(let e of b.stdout)n.stdout(e);for(let e of b.stderr)n.stderr(e);return n.exit(b.exitCode)}};function K(e,t,n){return{exitCode:e,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:n}}const Je=new Set([`bun`,`deno`,`node`,`tsx`]);function q(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function Ye(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return Je.has(t)}function Xe(e){let t=e[0],n=e[1],r=t===void 0?void 0:q(t);if(r!==void 0&&Ye(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:q(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:q(n)}return t===void 0?void 0:q(t)}function Ze(e){return new qe({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,plugins:[]})}function Qe(e){return{includeHidden:e?.includeHidden??!0,includePrompts:e?.includePrompts??!0}}const J=`https://json-schema.org/draft/2020-12/schema`;function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $e(e,t){let n=Qe(t),r={$schema:`https://dreamcli.kjanat.com/schemas/cli/v1.json`,name:e.name};return e.version!==void 0&&(r.version=e.version),e.description!==void 0&&(r.description=e.description),e.defaultCommand!==void 0&&(n.includeHidden||!e.defaultCommand.schema.hidden)&&(r.defaultCommand=e.defaultCommand.schema.name),r.commands=e.commands.filter(e=>n.includeHidden||!e.schema.hidden).map(e=>et(e.schema,n)),r}function et(e,t){let n={name:e.name};e.description!==void 0&&(n.description=e.description),e.aliases.length>0&&(n.aliases=[...e.aliases]),e.hidden&&(n.hidden=!0),e.examples.length>0&&(n.examples=e.examples.map(it));let r={};for(let[n,i]of Object.entries(e.flags))r[n]=X(i,t);return n.flags=r,n.args=e.args.map(tt),n.commands=e.commands.filter(e=>t.includeHidden||!e.hidden).map(e=>et(e,t)),n}function X(e,t){let n={kind:e.kind,presence:e.presence};return e.presence===`defaulted`&&Z(e.defaultValue)&&(n.defaultValue=e.defaultValue),e.aliases.length>0&&(n.aliases=[...e.aliases]),e.envVar!==void 0&&(n.envVar=e.envVar),e.configPath!==void 0&&(n.configPath=e.configPath),e.description!==void 0&&(n.description=e.description),e.enumValues!==void 0&&(n.enumValues=[...e.enumValues]),e.elementSchema!==void 0&&(n.elementSchema=X(e.elementSchema,t)),t.includePrompts&&e.prompt!==void 0&&(n.prompt=nt(e.prompt)),e.deprecated!==void 0&&(n.deprecated=e.deprecated),e.propagate&&(n.propagate=!0),n}function tt(e){let{name:t,schema:n}=e,r={name:t,kind:n.kind,presence:n.presence};return n.variadic&&(r.variadic=!0),n.stdinMode&&(r.stdinMode=!0),n.presence===`defaulted`&&Z(n.defaultValue)&&(r.defaultValue=n.defaultValue),n.description!==void 0&&(r.description=n.description),n.envVar!==void 0&&(r.envVar=n.envVar),n.enumValues!==void 0&&(r.enumValues=[...n.enumValues]),n.deprecated!==void 0&&(r.deprecated=n.deprecated),r}function nt(e){let t={kind:e.kind,message:e.message};switch(e.kind){case`input`:e.placeholder!==void 0&&(t.placeholder=e.placeholder);break;case`select`:e.choices!==void 0&&(t.choices=e.choices.map(rt));break;case`multiselect`:e.choices!==void 0&&(t.choices=e.choices.map(rt)),e.min!==void 0&&(t.min=e.min),e.max!==void 0&&(t.max=e.max);break;case`confirm`:break}return t}function rt(e){let t={value:e.value};return e.label!==void 0&&(t.label=e.label),e.description!==void 0&&(t.description=e.description),t}function it(e){let t={command:e.command};return e.description!==void 0&&(t.description=e.description),t}function at(e,t){let n=Qe(t);if(ot(e))return{$schema:J,...ct(e)};let r=[];for(let t of e.commands)!n.includeHidden&&t.schema.hidden||st(t.schema,``,r,n);if(r.length===1)return{$schema:J,...lt(r[0]??{})};if(r.length>0){let t=e.defaultCommand!==void 0&&(n.includeHidden||!e.defaultCommand.schema.hidden)?e.defaultCommand.schema.name:void 0;return{$schema:J,oneOf:t===void 0?r:r.map(e=>ut(e)===t?lt(e):e)}}return{$schema:J,type:`object`}}function ot(e){return`flags`in e&&`args`in e&&`middleware`in e&&`hasAction`in e}function st(e,t,n,r){let i=t?`${t}.${e.name}`:e.name;e.hasAction&&n.push(ct(e,i));for(let t of e.commands)!r.includeHidden&&t.hidden||st(t,i,n,r)}function ct(e,t){let n={},r=[];t!==void 0&&(n.command={const:t},r.push(`command`));for(let[t,i]of Object.entries(e.flags))n[t]=dt(i),i.presence===`required`&&r.push(t);for(let t of e.args)n[t.name]=ft(t.schema),t.schema.presence===`required`&&r.push(t.name);let i={type:`object`,properties:n,additionalProperties:!1};return r.length>0&&(i.required=r),i}function lt(e){let t=e.properties,n=e.required,r=Y(t)?{...t}:void 0,i=Array.isArray(n)?n.filter(e=>typeof e==`string`):void 0;r!==void 0&&delete r.command;let a=i?.filter(e=>e!==`command`),o={...e};return r!==void 0&&(o.properties=r),a!==void 0&&a.length>0?o.required=a:delete o.required,o}function ut(e){let t=e.properties;if(!Y(t))return;let n=t.command;return Y(n)&&typeof n.const==`string`?n.const:void 0}function dt(e){let t={};switch(e.kind){case`string`:t.type=`string`;break;case`number`:t.type=`number`;break;case`boolean`:t.type=`boolean`;break;case`enum`:t.type=`string`,e.enumValues!==void 0&&(t.enum=[...e.enumValues]);break;case`array`:t.type=`array`,e.elementSchema!==void 0&&(t.items=dt(e.elementSchema));break;case`custom`:break}return e.description!==void 0&&(t.description=e.description),e.presence===`defaulted`&&Z(e.defaultValue)&&(t.default=e.defaultValue),e.deprecated!==void 0&&(t.deprecated=!0),t}function ft(e){let t=pt(e),n=e.variadic?{type:`array`,items:t}:{...t};return e.description!==void 0&&(n.description=e.description),e.presence===`defaulted`&&Z(e.defaultValue)&&(n.default=e.defaultValue),e.deprecated!==void 0&&(n.deprecated=!0),n}function pt(e){switch(e.kind){case`string`:return{type:`string`};case`number`:return{type:`number`};case`enum`:{let t={type:`string`};return e.enumValues!==void 0&&(t.enum=[...e.enumValues]),t}case`custom`:return{}}}function Z(e,t=new WeakSet){if(e===void 0)return!1;if(e===null)return!0;let n=typeof e;if(n===`string`||n===`boolean`)return!0;if(n===`number`)return Number.isFinite(e);if(n===`function`||n===`symbol`||n===`bigint`)return!1;if(Array.isArray(e)){if(t.has(e))return!1;t.add(e);try{return e.every(e=>Z(e,t))}finally{t.delete(e)}}if(n===`object`){let n=e;if(!mt(n)||t.has(n))return!1;t.add(n);try{return Object.values(n).every(e=>Z(e,t))}finally{t.delete(n)}}return!1}function mt(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Q(e,t){return{kind:e,presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:void 0,enumValues:void 0,elementSchema:void 0,prompt:void 0,parseFn:void 0,deprecated:void 0,propagate:!1,...t}}var $=class e{schema;constructor(e){this.schema=e}default(t){return new e({...this.schema,presence:`defaulted`,defaultValue:t})}required(){return new e({...this.schema,presence:`required`})}alias(t){return new e({...this.schema,aliases:[...this.schema.aliases,t]})}env(t){return new e({...this.schema,envVar:t})}config(t){return new e({...this.schema,configPath:t})}describe(t){return new e({...this.schema,description:t})}prompt(t){return new e({...this.schema,prompt:t})}deprecated(t){return new e({...this.schema,deprecated:t??!0})}propagate(){return new e({...this.schema,propagate:!0})}};const ht={string(){return new $(Q(`string`))},number(){return new $(Q(`number`))},boolean(){return new $(Q(`boolean`,{presence:`defaulted`,defaultValue:!1}))},enum(e){return new $(Q(`enum`,{enumValues:e}))},array(e){return new $(Q(`array`,{elementSchema:e.schema}))},custom(e){return new $(Q(`custom`,{parseFn:e}))}};function gt(e){return{_handler:e}}export{z as ArgBuilder,qe as CLIBuilder,d as CLIError,je as CommandBuilder,$ as FlagBuilder,c as ParseError,j as SHELLS,a as ValidationError,Oe as arg,L as buildConfigSearchPaths,Ze as cli,B as command,De as configFormat,R as createArgSchema,m as createOutput,Q as createSchema,o as createTerminalPrompter,Ee as discoverConfig,ye as discoverPackageJson,ht as flag,n as formatHelp,w as generateBashCompletion,M as generateCompletion,at as generateInputSchema,$e as generateSchema,de as generateZshCompletion,Me as group,P as inferCliName,i as isCLIError,e as isParseError,h as isValidationError,gt as middleware,f as parse,Pe as plugin,l as resolve,u as resolvePromptConfig,t as tokenize};
1
+ import{FlagBuilder as e,createSchema as t,flag as n}from"./core/schema/flag.mjs";import{generateBashCompletion as r}from"./core/completion/shells/bash.mjs";import{generateFishCompletion as i}from"./core/completion/shells/fish.mjs";import{generatePowerShellCompletion as a}from"./core/completion/shells/powershell.mjs";import{CLIError as o,ParseError as s,ValidationError as c,isCLIError as l,isParseError as u,isValidationError as d}from"./core/errors/index.mjs";import{generateZshCompletion as f}from"./core/completion/shells/zsh.mjs";import{SHELLS as p,generateCompletion as m}from"./core/completion/index.mjs";import{formatHelp as h}from"./core/help/index.mjs";import{parse as g,tokenize as _}from"./core/parse/index.mjs";import{createTerminalPrompter as v,resolvePromptConfig as y}from"./core/prompt/index.mjs";import{resolve as b}from"./core/resolve/index.mjs";import{createOutput as x}from"./core/output/index.mjs";import{ArgBuilder as S,arg as C,createArgSchema as w}from"./core/schema/arg.mjs";import{CommandBuilder as T,command as E,group as D}from"./core/schema/command.mjs";import{plugin as O}from"./core/cli/plugin.mjs";import{discoverPackageJson as k,inferCliName as A}from"./core/config/package-json.mjs";import{buildConfigSearchPaths as j,configFormat as M,discoverConfig as N}from"./core/config/index.mjs";import{CLIBuilder as P,cli as F}from"./core/cli/index.mjs";import{definitionMetaSchema as I,generateInputSchema as L,generateSchema as R}from"./core/json-schema/index.mjs";import{middleware as z}from"./core/schema/middleware.mjs";export{S as ArgBuilder,P as CLIBuilder,o as CLIError,T as CommandBuilder,e as FlagBuilder,s as ParseError,p as SHELLS,c as ValidationError,C as arg,j as buildConfigSearchPaths,F as cli,E as command,M as configFormat,w as createArgSchema,x as createOutput,t as createSchema,v as createTerminalPrompter,I as definitionMetaSchema,N as discoverConfig,k as discoverPackageJson,n as flag,h as formatHelp,r as generateBashCompletion,m as generateCompletion,i as generateFishCompletion,L as generateInputSchema,a as generatePowerShellCompletion,R as generateSchema,f as generateZshCompletion,D as group,A as inferCliName,l as isCLIError,u as isParseError,d as isValidationError,z as middleware,g as parse,O as plugin,b as resolve,y as resolvePromptConfig,_ as tokenize};
@@ -0,0 +1,212 @@
1
+ import { WriteFn } from "../core/output/writer.mjs";
2
+ import { ReadFn } from "../core/prompt/index.mjs";
3
+
4
+ //#region src/runtime/adapter.d.ts
5
+ /**
6
+ * Runtime adapter interface.
7
+ *
8
+ * Defines the minimal contract between the platform-agnostic core and
9
+ * the host runtime (Node.js, Bun, Deno). Every platform-dependent
10
+ * operation flows through this interface — the core never calls
11
+ * `process.*`, `Deno.*`, or `Bun.*` directly.
12
+ *
13
+ * Adapters are designed to be:
14
+ * - **Immutable in shape:** all properties are readonly
15
+ * - **Minimal:** only the operations the framework actually needs
16
+ * - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * // Production: auto-detected
21
+ * cli('mycli').run(); // uses Node/Bun/Deno adapter
22
+ *
23
+ * // Test: explicit adapter
24
+ * cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
25
+ * ```
26
+ */
27
+ interface RuntimeAdapter {
28
+ /** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
29
+ readonly argv: readonly string[];
30
+ /**
31
+ * Environment variables.
32
+ * Values are `string | undefined` — mirrors Node's `process.env` semantics.
33
+ */
34
+ readonly env: Readonly<Record<string, string | undefined>>;
35
+ /** Current working directory (absolute path). */
36
+ readonly cwd: string;
37
+ /** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
38
+ readonly stdout: WriteFn;
39
+ /** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
40
+ readonly stderr: WriteFn;
41
+ /**
42
+ * Line reader for stdin. Used by the prompt engine for interactive input.
43
+ *
44
+ * Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
45
+ * indicating the user closed the input stream (treated as cancel).
46
+ */
47
+ readonly stdin: ReadFn;
48
+ /**
49
+ * Read all of stdin as a single string (for piped data).
50
+ *
51
+ * Returns the full stdin contents when data is piped (`stdinIsTTY` is
52
+ * false), or `null` when stdin is a TTY (no piped data available).
53
+ *
54
+ * Used by the resolve chain for args with `.stdin()` configured.
55
+ * Unlike {@link stdin} (which reads one line for prompts), this
56
+ * consumes the entire stream to EOF.
57
+ *
58
+ * @returns Full stdin contents as a string, or `null` if stdin is a TTY.
59
+ */
60
+ readonly readStdin: () => Promise<string | null>;
61
+ /** Whether stdout is connected to a TTY. */
62
+ readonly isTTY: boolean;
63
+ /** Whether stdin is connected to a TTY (used for prompt gating). */
64
+ readonly stdinIsTTY: boolean;
65
+ /**
66
+ * Exit the process with the given code.
67
+ * Must not return (divergent function).
68
+ */
69
+ readonly exit: (code: number) => never;
70
+ /**
71
+ * Read a file as UTF-8 text.
72
+ *
73
+ * Returns file contents on success, `null` if the file does not exist
74
+ * (ENOENT/NotFound). Throws on other I/O errors (permission denied,
75
+ * is-directory, etc.) — those indicate unexpected failures, not
76
+ * "try the next path".
77
+ *
78
+ * Used by config file discovery to probe multiple candidate paths.
79
+ */
80
+ readonly readFile: (path: string) => Promise<string | null>;
81
+ /**
82
+ * User home directory (absolute path).
83
+ *
84
+ * - Node/Bun: derived from `HOME` / `USERPROFILE` env
85
+ * - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
86
+ */
87
+ readonly homedir: string;
88
+ /**
89
+ * Platform-specific user configuration directory (absolute path).
90
+ *
91
+ * - Unix: `$XDG_CONFIG_HOME` or `~/.config`
92
+ * - Windows: `%APPDATA%` or `~\AppData\Roaming`
93
+ *
94
+ * Config discovery appends the app-specific subdirectory.
95
+ */
96
+ readonly configDir: string;
97
+ }
98
+ /**
99
+ * Options for creating a test adapter.
100
+ *
101
+ * All fields are optional — sensible defaults are applied for testing
102
+ * scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
103
+ * throws instead of killing the process).
104
+ */
105
+ interface TestAdapterOptions {
106
+ /** Raw argv (defaults to `['node', 'test']`). */
107
+ readonly argv?: readonly string[];
108
+ /** Environment variables (defaults to `{}`). */
109
+ readonly env?: Readonly<Record<string, string | undefined>>;
110
+ /** Working directory (defaults to `'/test'`). */
111
+ readonly cwd?: string;
112
+ /** Stdout writer (defaults to noop). */
113
+ readonly stdout?: WriteFn;
114
+ /** Stderr writer (defaults to noop). */
115
+ readonly stderr?: WriteFn;
116
+ /**
117
+ * Stdin line reader (defaults to returning `null` — immediate EOF).
118
+ *
119
+ * Use a custom {@linkcode ReadFn} to simulate user input in tests.
120
+ */
121
+ readonly stdin?: ReadFn;
122
+ /**
123
+ * Piped stdin data for testing args with `.stdin()` configured.
124
+ *
125
+ * When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
126
+ * string once, then `null` on subsequent reads. When absent, or when
127
+ * `stdinIsTTY` is `true`, `readStdin()` returns `null`.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * createTestAdapter({
132
+ * stdinData: '{"key": "value"}',
133
+ * })
134
+ * ```
135
+ */
136
+ readonly stdinData?: string;
137
+ /** TTY flag for stdout (defaults to `false`). */
138
+ readonly isTTY?: boolean;
139
+ /** TTY flag for stdin (defaults to `false`). */
140
+ readonly stdinIsTTY?: boolean;
141
+ /**
142
+ * Exit function (defaults to throwing {@linkcode ExitError}).
143
+ * The default throw-based exit allows tests to catch the exit code.
144
+ */
145
+ readonly exit?: (code: number) => never;
146
+ /**
147
+ * File reader stub (defaults to returning `null` — all files not found).
148
+ *
149
+ * Supply a custom function to simulate a virtual filesystem in tests:
150
+ * ```ts
151
+ * createTestAdapter({
152
+ * readFile: (path) => Promise.resolve(
153
+ * path === '/home/test/.config/myapp/config.json'
154
+ * ? '{"region":"eu"}'
155
+ * : null
156
+ * ),
157
+ * })
158
+ * ```
159
+ */
160
+ readonly readFile?: (path: string) => Promise<string | null>;
161
+ /** Home directory (defaults to `'/home/test'`). */
162
+ readonly homedir?: string;
163
+ /** Config directory (defaults to `'/home/test/.config'`). */
164
+ readonly configDir?: string;
165
+ }
166
+ /**
167
+ * Error thrown by adapter implementations that model process exit as an
168
+ * exception instead of terminating immediately.
169
+ *
170
+ * Runtime and CLI dispatch layers can catch this to perform real process
171
+ * termination, while tests can assert on exit codes without killing the
172
+ * runner:
173
+ *
174
+ * ```ts
175
+ * try {
176
+ * await cli.run({ adapter: createTestAdapter() });
177
+ * } catch (e) {
178
+ * if (e instanceof ExitError) expect(e.code).toBe(0);
179
+ * }
180
+ * ```
181
+ */
182
+ declare class ExitError extends Error {
183
+ /** Error name — always `'ExitError'` for `instanceof` checks. */
184
+ readonly name = "ExitError";
185
+ /** The exit code passed to `exit()`. */
186
+ readonly code: number;
187
+ /** Create an ExitError for the given process exit code. */
188
+ constructor(code: number);
189
+ }
190
+ /**
191
+ * Create a test runtime adapter with injectable process state.
192
+ *
193
+ * Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
194
+ * environment variables, TTY state, stdin, or config-file reads without
195
+ * touching the host process.
196
+ *
197
+ * @param options - Optional overrides for any adapter field.
198
+ * @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * const adapter = createTestAdapter({
203
+ * argv: ['node', 'cli.js', 'deploy', '--force'],
204
+ * env: { DEPLOY_REGION: 'us' },
205
+ * });
206
+ *
207
+ * const result = await cli('mycli').run({ adapter });
208
+ * ```
209
+ */
210
+ declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
211
+ //#endregion
212
+ export { ExitError, type RuntimeAdapter, type TestAdapterOptions, createTestAdapter };
@@ -1 +1 @@
1
- var e=class extends Error{name=`ExitError`;code;constructor(e){super(`Process exited with code ${e}`),this.code=e}};const t=()=>{},n=()=>Promise.resolve(null),r=()=>Promise.resolve(null);function i(i){let a=i?.stdinIsTTY??!1,o=a?void 0:i?.stdinData;return{argv:i?.argv??[`node`,`test`],env:i?.env??{},cwd:i?.cwd??`/test`,stdout:i?.stdout??t,stderr:i?.stderr??t,stdin:i?.stdin??n,readStdin:()=>{if(o===void 0)return Promise.resolve(null);let e=o;return o=void 0,Promise.resolve(e)},isTTY:i?.isTTY??!1,stdinIsTTY:a,exit:i?.exit??(t=>{throw new e(t)}),readFile:i?.readFile??r,homedir:i?.homedir??`/home/test`,configDir:i?.configDir??`/home/test/.config`}}export{i as n,e as t};
1
+ var e=class extends Error{name=`ExitError`;code;constructor(e){super(`Process exited with code ${e}`),this.code=e}};const t=()=>{},n=()=>Promise.resolve(null),r=()=>Promise.resolve(null);function i(i){let a=i?.stdinIsTTY??!1,o=a?void 0:i?.stdinData;return{argv:i?.argv??[`node`,`test`],env:i?.env??{},cwd:i?.cwd??`/test`,stdout:i?.stdout??t,stderr:i?.stderr??t,stdin:i?.stdin??n,readStdin:()=>{if(o===void 0)return Promise.resolve(null);let e=o;return o=void 0,Promise.resolve(e)},isTTY:i?.isTTY??!1,stdinIsTTY:a,exit:i?.exit??(t=>{throw new e(t)}),readFile:i?.readFile??r,homedir:i?.homedir??`/home/test`,configDir:i?.configDir??`/home/test/.config`}}export{e as ExitError,i as createTestAdapter};
@@ -0,0 +1,26 @@
1
+ import { RuntimeAdapter } from "./adapter.mjs";
2
+ import { GlobalForDetect } from "./detect.mjs";
3
+
4
+ //#region src/runtime/auto.d.ts
5
+ /**
6
+ * Create a runtime adapter for the current environment.
7
+ *
8
+ * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
9
+ * Unknown runtimes fall back to the Node adapter because most JS runtimes
10
+ * expose a Node-compatible `process` global.
11
+ *
12
+ * @param globals - Override `globalThis` for testing. Production callers
13
+ * should omit this parameter.
14
+ * @returns A {@linkcode RuntimeAdapter} for the detected runtime.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { cli } from '@kjanat/dreamcli';
19
+ *
20
+ * // Auto-detects Node/Bun/Deno and creates the right adapter
21
+ * cli('mycli').run(); // uses createAdapter() internally
22
+ * ```
23
+ */
24
+ declare function createAdapter(globals?: GlobalForDetect): RuntimeAdapter;
25
+ //#endregion
26
+ export { createAdapter };
@@ -0,0 +1 @@
1
+ import{assertRuntimeVersionSupported as e}from"./support.mjs";import{createNodeAdapter as t}from"./node.mjs";import{createBunAdapter as n}from"./bun.mjs";import{createDenoAdapter as r}from"./deno.mjs";import{detectRuntime as i}from"./detect.mjs";function a(e,t){switch(e){case`bun`:return t.Bun?.version;case`deno`:return t.Deno?.version?.deno;case`node`:return t.process?.versions?.node;case`unknown`:return;default:return e}}function o(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.args)&&typeof t.cwd==`function`&&typeof t.exit==`function`&&typeof t.readTextFile==`function`&&typeof t.env?.get==`function`&&typeof t.env.toObject==`function`&&typeof t.stdout?.writeSync==`function`&&typeof t.stdout.isTerminal==`function`&&typeof t.stderr?.writeSync==`function`&&typeof t.stdin?.isTerminal==`function`&&typeof t.stdin?.readable?.getReader==`function`}function s(e){let t=e.Deno;return o(t)?t:void 0}function c(o){let c=o??globalThis,l=i(c);switch(l!==`unknown`&&e(l,a(l,c)),l){case`bun`:return n();case`deno`:return r(s(c));case`node`:case`unknown`:return t();default:return l}}export{c as createAdapter};
@@ -0,0 +1,28 @@
1
+ import { RuntimeAdapter } from "./adapter.mjs";
2
+ import { NodeProcess } from "./node.mjs";
3
+
4
+ //#region src/runtime/bun.d.ts
5
+ /**
6
+ * Create a runtime adapter backed by Bun's Node-compatible `process` global.
7
+ *
8
+ * Bun exposes `globalThis.process` with the same shape as Node.js, so this
9
+ * delegates entirely to {@link createNodeAdapter}. If Bun-specific optimizations
10
+ * are needed in the future (e.g. `Bun.write` for I/O), they can be layered
11
+ * here without changing the public API.
12
+ *
13
+ * @param proc - Override the process object (useful for testing the adapter itself).
14
+ * @returns A {@linkcode RuntimeAdapter} backed by Bun's process state.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { cli } from '@kjanat/dreamcli';
19
+ * import { createBunAdapter } from '@kjanat/dreamcli/runtime';
20
+ *
21
+ * cli('mycli')
22
+ * .command(deploy)
23
+ * .run({ adapter: createBunAdapter() });
24
+ * ```
25
+ */
26
+ declare function createBunAdapter(proc?: NodeProcess): RuntimeAdapter;
27
+ //#endregion
28
+ export { createBunAdapter };
@@ -0,0 +1 @@
1
+ import{assertRuntimeVersionSupported as e}from"./support.mjs";import{createNodeAdapter as t}from"./node.mjs";function n(e){return e?.versions?.bun===void 0?globalThis.Bun?.version:e.versions.bun}function r(r){return e(`bun`,n(r)),t(r)}export{r as createBunAdapter};
@@ -0,0 +1,76 @@
1
+ import { RuntimeAdapter } from "./adapter.mjs";
2
+
3
+ //#region src/runtime/deno.d.ts
4
+ /**
5
+ * Minimal subset of the Deno namespace needed by the adapter.
6
+ *
7
+ * We avoid `@types/deno` to keep the core runtime-agnostic at the type level.
8
+ * This interface declares only what `createDenoAdapter` actually reads.
9
+ *
10
+ * The `env` property is optional because it requires `--allow-env` permission.
11
+ * When permission is denied, the adapter catches the error and falls back to
12
+ * an empty env object.
13
+ */
14
+ interface DenoNamespace {
15
+ /** Build target metadata (OS detection). */
16
+ readonly build: {
17
+ readonly os: 'darwin' | 'linux' | 'android' | 'windows' | 'freebsd' | 'netbsd' | 'aix' | 'solaris' | 'illumos';
18
+ };
19
+ /** Deno version info — used for minimum-version guard. */
20
+ readonly version?: {
21
+ readonly deno?: string;
22
+ };
23
+ /** Raw command-line args (excludes the binary/script — Deno pre-strips them). */
24
+ readonly args: readonly string[];
25
+ /** Environment variable access (requires `--allow-env`). */
26
+ readonly env: {
27
+ /** Get a single env var. Returns `undefined` if unset or permission denied. */get(key: string): string | undefined; /** Get all env vars as a plain object. Throws on permission denied. */
28
+ toObject(): Record<string, string>;
29
+ };
30
+ /** Current working directory (may throw if `--allow-read` is denied for cwd). */
31
+ cwd(): string;
32
+ /** Standard output — synchronous byte writer with TTY detection. */
33
+ readonly stdout: {
34
+ /** Write raw bytes to stdout synchronously. */writeSync(p: Uint8Array): number; /** Whether stdout is connected to a TTY. */
35
+ isTerminal(): boolean;
36
+ };
37
+ /** Standard error — synchronous byte writer. */
38
+ readonly stderr: {
39
+ /** Write raw bytes to stderr synchronously. */writeSync(p: Uint8Array): number;
40
+ };
41
+ /** Standard input — TTY detection and readable byte stream. */
42
+ readonly stdin: {
43
+ /** Whether stdin is connected to a TTY. */isTerminal(): boolean; /** Readable stream for stdin bytes. */
44
+ readonly readable: ReadableStream<Uint8Array>;
45
+ };
46
+ /** Exit the process with the given code. */
47
+ exit(code: number): never;
48
+ /** Read a file as UTF-8 text (requires `--allow-read`). */
49
+ readTextFile(path: string): Promise<string>;
50
+ }
51
+ /**
52
+ * Create a runtime adapter backed by the Deno namespace.
53
+ *
54
+ * Reads `Deno.args`, `Deno.env`, `Deno.cwd()`, and wraps Deno's stream-based
55
+ * I/O into the {@linkcode WriteFn}/{@linkcode ReadFn} functions expected by the framework.
56
+ *
57
+ * Unlike Node/Bun, Deno strips the binary and script path from `Deno.args`.
58
+ * The adapter prepends synthetic entries (`['deno', 'run']`) so the argv
59
+ * shape matches the {@linkcode RuntimeAdapter} contract (binary + script + user args).
60
+ *
61
+ * @param ns - Override the Deno namespace (useful for testing the adapter itself).
62
+ * @returns A {@linkcode RuntimeAdapter} backed by Deno's namespace APIs.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { cli } from '@kjanat/dreamcli';
67
+ * import { createDenoAdapter } from '@kjanat/dreamcli/runtime';
68
+ *
69
+ * cli('mycli')
70
+ * .command(deploy)
71
+ * .run({ adapter: createDenoAdapter() });
72
+ * ```
73
+ */
74
+ declare function createDenoAdapter(ns?: DenoNamespace): RuntimeAdapter;
75
+ //#endregion
76
+ export { type DenoNamespace, createDenoAdapter };
@@ -0,0 +1,2 @@
1
+ import{resolveConfigDirectory as e,resolveHomeDirectory as t}from"./paths.mjs";import{assertRuntimeVersionSupported as n}from"./support.mjs";function r(e,t){if(typeof e!=`object`||!e||!(`name`in e))return!1;let n=e;return typeof n.name==`string`&&n.name===t}function i(e){try{return e.env.toObject()}catch(e){if(r(e,`PermissionDenied`))return{};throw e}}function a(e){try{return e.cwd()}catch(e){if(r(e,`PermissionDenied`))return`/`;throw e}}function o(e){let t=e??s();n(`deno`,t.version?.deno);let o=new TextEncoder,f=[`deno`,`run`,...t.args],p=i(t),m=a(t),h=e=>{t.stdout.writeSync(o.encode(e))},g=e=>{t.stderr.writeSync(o.encode(e))},_=l(t),v=async e=>{try{return await t.readTextFile(e)}catch(e){if(r(e,`NotFound`)||r(e,`PermissionDenied`))return null;throw e}},y=u(p,t.build.os===`windows`),b=d(p,y,t.build.os===`windows`),x=t.stdin.isTerminal();return{argv:f,env:p,cwd:m,stdout:h,stderr:g,stdin:_,readStdin:()=>c(t,x),isTTY:t.stdout.isTerminal(),stdinIsTTY:x,exit:e=>t.exit(e),readFile:v,homedir:y,configDir:b}}function s(){return globalThis.Deno}async function c(e,t){if(t)return null;let n=e.stdin.readable.getReader(),r=new TextDecoder,i=[];try{for(;;){let{value:e,done:t}=await n.read();if(t){i.push(r.decode());break}i.push(r.decode(e,{stream:!0}))}}finally{n.releaseLock()}return i.join(``)}function l(e){let t=new TextDecoder,n=``,r=!1;return async()=>{let i=e.stdin.readable.getReader();try{for(;;){let e=n.indexOf(`
2
+ `);if(e!==-1){let t=n.slice(0,e).replace(/\r$/,``);return n=n.slice(e+1),t}if(r){if(n.length===0)return null;let e=n;return n=``,e}let{value:a,done:o}=await i.read();if(o){n+=t.decode(),r=!0;continue}n+=t.decode(a,{stream:!0})}}finally{i.releaseLock()}}}function u(e,n){return t(e,n)}function d(t,n,r){return e(t,r,n)}export{o as createDenoAdapter};
@@ -0,0 +1,86 @@
1
+ //#region src/runtime/detect.d.ts
2
+ /**
3
+ * Auto-detects the current JavaScript runtime environment.
4
+ *
5
+ * Uses `globalThis` feature detection (version globals) to identify
6
+ * the runtime without importing platform-specific modules. This is
7
+ * the recommended approach because each runtime defines a unique
8
+ * global marker:
9
+ *
10
+ * - **Bun:** `globalThis.Bun.version` (string)
11
+ * - **Deno:** `globalThis.Deno.version` (object with `deno` key)
12
+ * - **Node:** `globalThis.process.versions.node` (string)
13
+ *
14
+ * Detection order matters: Bun provides a Node-compatible `process`
15
+ * global, so it must be checked *before* Node to avoid misidentification.
16
+ *
17
+ * @module @kjanat/dreamcli/runtime/detect
18
+ */
19
+ /**
20
+ * Known JavaScript runtime environments.
21
+ *
22
+ * - `'node'` — Node.js
23
+ * - `'bun'` — Bun
24
+ * - `'deno'` — Deno
25
+ * - `'unknown'` — Unrecognized environment
26
+ */
27
+ type Runtime = 'node' | 'bun' | 'deno' | 'unknown';
28
+ /**
29
+ * All known runtime values as a readonly tuple.
30
+ *
31
+ * Useful for validation, iteration, and exhaustiveness checks.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * if (RUNTIMES.includes(value)) {
36
+ * // value is a valid Runtime
37
+ * }
38
+ * ```
39
+ */
40
+ declare const RUNTIMES: readonly ['node', 'bun', 'deno', 'unknown'];
41
+ /**
42
+ * Minimal `globalThis` shape used for runtime detection.
43
+ *
44
+ * Each field is optional — only the present one identifies the runtime.
45
+ * Typed as `unknown` where we only need truthiness; version fields are
46
+ * typed just enough to distinguish runtimes safely.
47
+ */
48
+ interface GlobalForDetect {
49
+ /** Present when running on Bun. */
50
+ readonly Bun?: {
51
+ readonly version?: string;
52
+ };
53
+ /** Present when running on Deno. */
54
+ readonly Deno?: {
55
+ readonly version?: {
56
+ readonly deno?: string;
57
+ };
58
+ };
59
+ /** Present on Node.js (and Bun, which mimics it). */
60
+ readonly process?: {
61
+ readonly versions?: {
62
+ readonly node?: string;
63
+ readonly bun?: string;
64
+ };
65
+ };
66
+ }
67
+ /**
68
+ * Detect the current JavaScript runtime.
69
+ *
70
+ * Uses `globalThis` feature detection to identify the host runtime.
71
+ * Detection order is significant: Bun is checked before Node because
72
+ * Bun exposes a Node-compatible `process` global.
73
+ *
74
+ * @param globals - Override `globalThis` for testing. Production callers
75
+ * should omit this parameter.
76
+ * @returns The detected {@link Runtime} identifier.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * const rt = detectRuntime();
81
+ * // rt === 'node' | 'bun' | 'deno' | 'unknown'
82
+ * ```
83
+ */
84
+ declare function detectRuntime(globals?: GlobalForDetect): Runtime;
85
+ //#endregion
86
+ export { type GlobalForDetect, RUNTIMES, type Runtime, detectRuntime };
@@ -0,0 +1 @@
1
+ const e=[`node`,`bun`,`deno`,`unknown`];function t(e){let t=e??globalThis;return typeof t.Bun?.version==`string`?`bun`:typeof t.Deno?.version?.deno==`string`?`deno`:typeof t.process?.versions?.node==`string`?`node`:`unknown`}export{e as RUNTIMES,t as detectRuntime};
@@ -0,0 +1,7 @@
1
+ import { ExitError, RuntimeAdapter, TestAdapterOptions, createTestAdapter } from "./adapter.mjs";
2
+ import { GlobalForDetect, RUNTIMES, Runtime, detectRuntime } from "./detect.mjs";
3
+ import { createAdapter } from "./auto.mjs";
4
+ import { NodeProcess, createNodeAdapter } from "./node.mjs";
5
+ import { createBunAdapter } from "./bun.mjs";
6
+ import { DenoNamespace, createDenoAdapter } from "./deno.mjs";
7
+ export { type DenoNamespace, ExitError, type GlobalForDetect, type NodeProcess, RUNTIMES, type Runtime, type RuntimeAdapter, type TestAdapterOptions, createAdapter, createBunAdapter, createDenoAdapter, createNodeAdapter, createTestAdapter, detectRuntime };
@@ -0,0 +1,65 @@
1
+ import { RuntimeAdapter } from "./adapter.mjs";
2
+
3
+ //#region src/runtime/node.d.ts
4
+ /**
5
+ * Minimal subset of the Node.js `process` object needed by the adapter.
6
+ *
7
+ * We avoid importing `@types/node` to keep the core runtime-agnostic
8
+ * at the type level. This interface declares only what `createNodeAdapter`
9
+ * actually reads from the global.
10
+ */
11
+ interface NodeProcess {
12
+ /** Raw process arguments (`[binary, script, ...userArgs]`). */
13
+ readonly argv: readonly string[];
14
+ /** Environment variables (values are `undefined` for unset keys). */
15
+ readonly env: Readonly<Record<string, string | undefined>>;
16
+ /** Runtime version strings — used for version-guard checks. */
17
+ readonly versions?: {
18
+ readonly node?: string;
19
+ readonly bun?: string;
20
+ };
21
+ /** Return the current working directory. */
22
+ cwd(): string;
23
+ /** Platform identifier (e.g. `'linux'`, `'darwin'`, `'win32'`). */
24
+ readonly platform: string;
25
+ /** Standard input stream with TTY detection and async iteration. */
26
+ readonly stdin: {
27
+ readonly isTTY?: boolean; /** Async iterable for reading all of stdin (used by readStdin). */
28
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
29
+ };
30
+ /** Standard output stream with TTY detection and write. */
31
+ readonly stdout: {
32
+ readonly isTTY?: boolean;
33
+ write(data: string): unknown;
34
+ };
35
+ /** Standard error stream with write. */
36
+ readonly stderr: {
37
+ write(data: string): unknown;
38
+ };
39
+ /** Terminate the process with the given exit code. */
40
+ exit(code: number): never;
41
+ }
42
+ /**
43
+ * Create a runtime adapter backed by Node.js `process` globals.
44
+ *
45
+ * Reads `process.argv`, `process.env`, `process.cwd()`, and wraps
46
+ * `process.stdout.write`/`process.stderr.write` as {@linkcode WriteFn} functions.
47
+ *
48
+ * Also works on Bun, which provides a Node-compatible `process` global.
49
+ *
50
+ * @param proc - Override the process object (useful for testing the adapter itself).
51
+ * @returns A {@linkcode RuntimeAdapter} backed by Node.js process state.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * import { cli } from '@kjanat/dreamcli';
56
+ * import { createNodeAdapter } from '@kjanat/dreamcli/runtime/node';
57
+ *
58
+ * cli('mycli')
59
+ * .command(deploy)
60
+ * .run({ adapter: createNodeAdapter() });
61
+ * ```
62
+ */
63
+ declare function createNodeAdapter(proc?: NodeProcess): RuntimeAdapter;
64
+ //#endregion
65
+ export { type NodeProcess, createNodeAdapter };