@kjanat/dreamcli 0.0.0 → 1.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.
- package/CHANGELOG.md +667 -0
- package/LICENSE +22 -0
- package/README.md +370 -0
- package/dist/adapter-B37d9oia.mjs +1 -0
- package/dist/adapter-CCSh5juX.cjs +1 -0
- package/dist/adapter-DIwO-q7K.d.mts +3447 -0
- package/dist/adapter-DQnxxLiE.d.cts +3447 -0
- package/dist/auto-5cjZaF9V.mjs +3 -0
- package/dist/auto-B0eSgoDw.cjs +3 -0
- package/dist/index.cjs +10 -0
- package/dist/index.d.cts +920 -0
- package/dist/index.d.mts +920 -0
- package/dist/index.mjs +10 -0
- package/dist/runtime.cjs +1 -0
- package/dist/runtime.d.cts +253 -0
- package/dist/runtime.d.mts +253 -0
- package/dist/runtime.mjs +1 -0
- package/dist/testkit-CEDYPvhF.mjs +14 -0
- package/dist/testkit-ClIKijxC.cjs +14 -0
- package/dist/testkit.cjs +1 -0
- package/dist/testkit.d.cts +25 -0
- package/dist/testkit.d.mts +25 -0
- package/dist/testkit.mjs +1 -0
- package/examples/basic.ts +33 -0
- package/examples/gh/package.json +48 -0
- package/examples/gh/src/commands/auth.ts +66 -0
- package/examples/gh/src/commands/issue.ts +120 -0
- package/examples/gh/src/commands/pr.ts +125 -0
- package/examples/gh/src/data/issues.yaml +5 -0
- package/examples/gh/src/data/issues.yaml.d.ts +17 -0
- package/examples/gh/src/data/pull-requests.yaml +7 -0
- package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
- package/examples/gh/src/lib/auth.ts +37 -0
- package/examples/gh/src/lib/utils.ts +17 -0
- package/examples/gh/src/main.test.ts +306 -0
- package/examples/gh/src/main.ts +38 -0
- package/examples/gh/tsconfig.json +37 -0
- package/examples/interactive.ts +66 -0
- package/examples/json-mode.ts +93 -0
- package/examples/middleware.ts +71 -0
- package/examples/multi-command.ts +66 -0
- package/examples/spinner-progress.ts +49 -0
- package/examples/testing.ts +145 -0
- package/examples/tsconfig.json +17 -0
- package/package.json +123 -2
- package/src/core/cli/AGENTS.md +72 -0
- package/src/core/cli/dispatch.ts +282 -0
- package/src/core/cli/index.ts +1425 -0
- package/src/core/cli/plugin.ts +111 -0
- package/src/core/cli/propagate.ts +97 -0
- package/src/core/cli/root-help.ts +269 -0
- package/src/core/cli/root-surface.ts +74 -0
- package/src/core/completion/AGENTS.md +72 -0
- package/src/core/completion/completion-test-helpers.ts +48 -0
- package/src/core/completion/index.ts +82 -0
- package/src/core/completion/shells/bash.ts +456 -0
- package/src/core/completion/shells/fish.ts +24 -0
- package/src/core/completion/shells/powershell.ts +24 -0
- package/src/core/completion/shells/shared.ts +283 -0
- package/src/core/completion/shells/zsh.ts +376 -0
- package/src/core/config/index.ts +404 -0
- package/src/core/config/package-json.ts +216 -0
- package/src/core/errors/index.ts +178 -0
- package/src/core/help/index.ts +559 -0
- package/src/core/json-schema/index.ts +705 -0
- package/src/core/output/AGENTS.md +69 -0
- package/src/core/output/activity.ts +568 -0
- package/src/core/output/display-value.ts +48 -0
- package/src/core/output/index.ts +704 -0
- package/src/core/output/writer.ts +46 -0
- package/src/core/parse/index.ts +643 -0
- package/src/core/prompt/index.ts +566 -0
- package/src/core/resolve/AGENTS.md +69 -0
- package/src/core/resolve/index.ts +1331 -0
- package/src/core/schema/AGENTS.md +61 -0
- package/src/core/schema/activity.ts +237 -0
- package/src/core/schema/arg.ts +707 -0
- package/src/core/schema/command.ts +1263 -0
- package/src/core/schema/flag.ts +651 -0
- package/src/core/schema/index.ts +82 -0
- package/src/core/schema/middleware.ts +171 -0
- package/src/core/schema/prompt.ts +148 -0
- package/src/core/schema/run.ts +187 -0
- package/src/core/testkit/AGENTS.md +55 -0
- package/src/core/testkit/index.ts +365 -0
- package/src/index.ts +164 -0
- package/src/runtime/AGENTS.md +74 -0
- package/src/runtime/adapter.ts +300 -0
- package/src/runtime/auto.ts +110 -0
- package/src/runtime/bun.ts +55 -0
- package/src/runtime/deno.ts +355 -0
- package/src/runtime/detect.ts +102 -0
- package/src/runtime/index.ts +21 -0
- package/src/runtime/node-builtins.d.ts +23 -0
- package/src/runtime/node.ts +278 -0
- package/src/runtime/paths.ts +56 -0
- package/src/runtime/support.ts +119 -0
- package/src/runtime/test-helpers.ts +40 -0
- package/src/runtime.ts +31 -0
- package/src/testkit.ts +23 -0
- package/src/version.ts +20 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
var e=class extends Error{name=`CLIError`;code;exitCode;suggest;details;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.code=t.code,this.exitCode=t.exitCode??1,this.suggest=t.suggest,this.details=t.details}toJSON(){return{name:this.name,code:this.code,message:this.message,exitCode:this.exitCode,...this.suggest!==void 0&&{suggest:this.suggest},...this.details!==void 0&&{details:this.details}}}},t=class extends e{name=`ParseError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}},n=class extends e{name=`ValidationError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}};function r(t){return t instanceof e}function i(e){return e instanceof t}function a(e){return e instanceof n}function o(e){if(e==null)return``;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);if(e instanceof Date)return Number.isNaN(e.getTime())?`Invalid Date`:e.toISOString();if(typeof e==`function`)return e.name.length>0?`[Function: ${e.name}]`:`[Function]`;try{return JSON.stringify(e)??`[unserializable]`}catch{return`[unserializable]`}}function s(e){return{width:e?.width??80,binName:e?.binName,isDefaultHelp:e?.isDefaultHelp??!1}}function c(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function l(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(`
|
|
2
|
+
`)}function u(e){return typeof e==`string`?`[deprecated: ${e}]`:`[deprecated]`}function d(e){return e===void 0?`undefined`:e===null?`null`:o(e)}function ee(e,t){let n=[],r=t.aliases.find(e=>e.length===1);return r!==void 0&&n.push(`-${r},`),n.push(`--${e}`),t.kind!==`boolean`&&n.push(f(t)),n.join(` `)}function f(e){switch(e.kind){case`string`:return`<string>`;case`number`:return`<number>`;case`enum`:return`<${(e.enumValues??[]).join(`|`)}>`;case`array`:return`<${e.elementSchema===void 0?`value`:f(e.elementSchema).slice(1,-1)}>...`;case`boolean`:return``;case`custom`:return`<value>`}}function p(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(u(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.configPath!==void 0&&t.push(`[config: ${e.configPath}]`),e.prompt!==void 0&&t.push(`[prompt]`),e.presence===`required`?t.push(`[required]`):e.presence===`defaulted`&&e.kind!==`boolean`&&t.push(`(default: ${d(e.defaultValue)})`),t.join(` `)}function te(e){let t=Object.keys(e);if(t.length===0)return[];let n=[...t].sort((t,n)=>{let r=e[t],i=e[n];if(r===void 0||i===void 0)return 0;let a=r.aliases.some(e=>e.length===1),o=i.aliases.some(e=>e.length===1);return a&&!o?-1:!a&&o?1:t.localeCompare(n)}),r=[];for(let t of n){let n=e[t];n!==void 0&&r.push({left:ee(t,n),description:p(n)})}return r}function m(e){let{name:t,schema:n}=e,r=n.kind===`enum`&&n.enumValues!==void 0?n.enumValues.join(`|`):t,i=n.variadic?`...`:``;return n.presence===`required`?`<${r}>${i}`:`[${r}]${i}`}function ne(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(u(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.presence===`defaulted`&&t.push(`(default: ${d(e.defaultValue)})`),t.join(` `)}function h(e,t){let n=s(t),r=[];r.push(re(e,n)),e.description!==void 0&&r.push(e.description);let i=e.commands.filter(e=>!e.hidden);return i.length>0&&r.push(oe(i,n)),e.args.length>0&&r.push(ie(e.args,n)),Object.keys(e.flags).length>0&&r.push(ae(e.flags,n)),e.examples.length>0&&r.push(se(e.examples)),r}function g(e,t){return`${h(e,t).join(`
|
|
3
|
+
|
|
4
|
+
`)}\n`}function re(e,t){let n=[`Usage:`],r=t.binName===void 0||t.isDefaultHelp&&t.binName===e.name?e.name:`${t.binName} ${e.name}`;n.push(r),e.commands.length>0&&n.push(`<command>`),Object.keys(e.flags).length>0&&n.push(`[flags]`);for(let t of e.args)n.push(m(t));return n.join(` `)}function ie(e,t){let n=[`Arguments:`],r=0,i=[];for(let t of e){let e=` ${m(t)}`,n=ne(t.schema);i.push({left:e,desc:n}),e.length>r&&(r=e.length)}let a=r+2;for(let{left:e,desc:r}of i)if(r.length===0)n.push(e);else{let i=c(e,a),o=l(r,t.width,a);n.push(`${i}${o}`)}return n.join(`
|
|
5
|
+
`)}function ae(e,t){let n=[`Flags:`],r=te(e);if(r.length===0)return``;let i=0;for(let e of r){let t=` ${e.left}`;t.length>i&&(i=t.length)}let a=i+2;for(let e of r){let r=` ${e.left}`;if(e.description.length===0)n.push(r);else{let i=c(r,a),o=l(e.description,t.width,a);n.push(`${i}${o}`)}}return n.join(`
|
|
6
|
+
`)}function oe(e,t){let n=[`Commands:`],r=0;for(let t of e)t.name.length>r&&(r=t.name.length);let i=2+r+2;for(let r of e){let e=` ${r.name}`,a=r.description??``;if(a.length===0)n.push(e);else{let r=c(e,i),o=l(a,t.width,i);n.push(`${r}${o}`)}}return n.join(`
|
|
7
|
+
`)}function se(e){let t=[`Examples:`];for(let n of e)n.description===void 0?t.push(` $ ${n.command}`):(t.push(` ${n.description}:`),t.push(` $ ${n.command}`));return t.join(`
|
|
8
|
+
`)}function _(e,t){e(`${t}\n`)}const ce={update(){},succeed(){},fail(){},stop(){},wrap(e){return e}},le={increment(){},update(){},done(){},fail(){}};var ue=class{stopped=!1;constructor(e,t){this.write=t,_(t,e)}update(e){}succeed(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}stop(){this.stopped||=!0}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},de=class{stopped=!1;constructor(e,t){this.write=t,e!==void 0&&_(t,e)}increment(e){}update(e){}done(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}};const v=`\x1B[?25l`,y=`\x1B[?25h`,b=`\x1B[2K`,x=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];var S=class{stopped=!1;timer;frameIndex=0;text;constructor(e,t){this.write=t,this.text=e,t(v),this.render(),this.timer=setInterval(()=>{this.frameIndex=(this.frameIndex+1)%x.length,this.render()},80)}render(){let e=x[this.frameIndex]??x[0];this.write(`\r${b}${e} ${this.text}`)}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${b}${y}`)}update(e){this.stopped||(this.text=e,this.render())}succeed(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✗ ${e}`))}stop(){this.stopped||(this.stopped=!0,this.cleanup())}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},C=class{stopped=!1;timer;current=0;total;label;pulsePos=0;pulseDir=1;constructor(e,t){this.write=t,this.total=e.total,this.label=e.label??``,t(v),this.render(),this.total===void 0&&(this.timer=setInterval(()=>{this.advancePulse(),this.render()},80))}advancePulse(){this.pulsePos+=this.pulseDir,this.pulsePos+3>20?(this.pulseDir=-1,this.pulsePos=17):this.pulsePos<0&&(this.pulseDir=1,this.pulsePos=0)}render(){let e=this.total===void 0?this.renderIndeterminate():this.renderDeterminate(this.total),t=this.label.length>0?` ${this.label}`:``;this.write(`\r${b}${e}${t}`)}renderDeterminate(e){let t=e>0?Math.max(0,Math.min(this.current/e,1)):0,n=Math.round(t*20),r=20-n,i=Math.round(t*100);return`[${`█`.repeat(n)}${`░`.repeat(r)}] ${String(i)}%`}renderIndeterminate(){let e=``;for(let t=0;t<20;t++)e+=t>=this.pulsePos&&t<this.pulsePos+3?`█`:`░`;return`[${e}]`}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${b}${y}`)}increment(e){this.stopped||(this.current+=e??1,this.render())}update(e){this.stopped||(this.current=e,this.render())}done(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✗ ${e}`))}},fe=class{stopped=!1;constructor(e,t){this.events=t,t.push({type:`spinner:start`,text:e})}update(e){this.stopped||this.events.push({type:`spinner:update`,text:e})}succeed(e){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:succeed`,text:e??``}))}fail(e){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:fail`,text:e??``}))}stop(){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:stop`}))}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},pe=class{stopped=!1;constructor(e,t){this.events=t,t.push({type:`progress:start`,label:e.label??``,total:e.total})}increment(e){this.stopped||this.events.push({type:`progress:increment`,delta:e??1})}update(e){this.stopped||this.events.push({type:`progress:update`,value:e})}done(e){this.stopped||(this.stopped=!0,this.events.push({type:`progress:done`,text:e}))}fail(e){this.stopped||(this.stopped=!0,this.events.push({type:`progress:fail`,text:e}))}};const w=()=>{};function T(e){return{stdout:e?.stdout??w,stderr:e?.stderr??w,isTTY:e?.isTTY??!1,verbosity:e?.verbosity??`normal`,jsonMode:e?.jsonMode??!1}}var E=class{options;jsonMode;isTTY;constructor(e){this.options=e,this.jsonMode=e.jsonMode,this.isTTY=e.isTTY}log(e){_(this.options.jsonMode?this.options.stderr:this.options.stdout,e)}info(e){this.options.verbosity!==`quiet`&&_(this.options.jsonMode?this.options.stderr:this.options.stdout,e)}warn(e){_(this.options.stderr,e)}error(e){_(this.options.stderr,e)}json(e){_(this.options.stdout,JSON.stringify(e))}table(e,t,n){let{columns:r,options:i}=ge(t,n),a=ve(this.options.jsonMode,i),o=r??he(e);if(a===`json`){this.json(_e(e,o));return}let s=xe(e,o);s.length!==0&&_(ye(this.options,a,i),s)}activeCleanup;stopActive(){this.activeCleanup!==void 0&&(this.activeCleanup(),this.activeCleanup=void 0)}spinner(e,t){let n=t?.fallback??`silent`;if(this.options.jsonMode||!this.options.isTTY&&n===`silent`)return ce;if(this.stopActive(),this.options.isTTY){let t=new S(e,this.options.stderr);return this.activeCleanup=()=>t.stop(),t}let r=new ue(e,this.options.stderr);return this.activeCleanup=()=>r.stop(),r}progress(e){let t=e.fallback??`silent`;if(this.options.jsonMode||!this.options.isTTY&&t===`silent`)return le;if(this.stopActive(),this.options.isTTY){let t=new C(e,this.options.stderr);return this.activeCleanup=()=>t.done(),t}let n=new de(e.label,this.options.stderr);return this.activeCleanup=()=>n.done(),n}},me=class extends E{constructor(e,t){super(e),this.activity=t}spinner(e,t){return new fe(e,this.activity)}progress(e){return new pe(e,this.activity)}};function he(e){let t=e[0];return t===void 0?[]:Object.keys(t).map(e=>({key:e}))}function D(e){return Array.isArray(e)}function ge(e,t){return t===void 0?D(e)?{columns:e,options:t}:{columns:void 0,options:e}:{columns:D(e)?e:void 0,options:t}}function _e(e,t){return e.map(e=>Object.fromEntries(t.map(t=>[t.key,e[t.key]])))}function ve(e,t){switch(t?.format){case`json`:return`json`;case`text`:return`text`;case`auto`:case void 0:return e?`json`:`text`}}function ye(e,t,n){return t===`text`&&n!==void 0&&`stream`in n&&n.stream!==void 0?n.stream===`stderr`?e.stderr:e.stdout:e.jsonMode?e.stderr:e.stdout}function be(e){return o(e)}function xe(e,t){if(e.length===0||t.length===0)return``;let n=t.map(e=>e.header??e.key),r=e.map(e=>t.map(t=>be(e[t.key]))),i=n.map((e,t)=>{let n=e.length;for(let e of r){let r=e[t];r!==void 0&&r.length>n&&(n=r.length)}return n});return[n.map((e,t)=>e.padEnd(i[t]??0)).join(` `),i.map(e=>`-`.repeat(e)).join(` `),...r.map(e=>e.map((e,t)=>e.padEnd(i[t]??0)).join(` `))].join(`
|
|
9
|
+
`)}function Se(e){return new E(T(e))}function O(e){let t={stdout:[],stderr:[],activity:[]};return[new me(T({...e,stdout:e=>t.stdout.push(e),stderr:e=>t.stderr.push(e)}),t.activity),t]}function k(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function A(e){let t=new Map;for(let[n,r]of Object.entries(e)){t.set(n,[n,r]);for(let e of r.aliases)t.set(e,[n,r])}return t}function j(e){return e.kind!==`boolean`}function M(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for flag --${e}`,{code:`INVALID_VALUE`,details:{flag:e,value:n,expected:`number`}});return r}case`boolean`:if(n===`true`||n===`1`)return!0;if(n===`false`||n===`0`)return!1;throw new t(`Invalid boolean value '${n}' for flag --${e}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,value:n,expected:`boolean`}});case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum flag --${e} is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{flag:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for flag --${e}. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,value:n,allowed:i}});return n}case`array`:return r.elementSchema?M(e,n,r.elementSchema):n;case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse flag --${e}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,value:n},cause:r})}}}function N(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for argument <${e}>`,{code:`INVALID_VALUE`,details:{arg:e,value:n,expected:`number`}});return r}case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum argument <${e}> is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{arg:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for argument <${e}>. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n,allowed:i}});return n}case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse argument <${e}>: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n},cause:r})}}}function P(e,t){let n=k(t),r=A(e.flags),i={},a=[],o=0;for(;o<n.length;){let e=n[o];if(e===void 0)break;if(e.kind===`separator`){o++;continue}if(e.kind===`positional`){a.push(e.value),o++;continue}if(e.kind===`long-flag`){o=Ce(e,n,o,r,i);continue}o=we(e,n,o,r,i)}return{flags:i,args:Te(e.args,a)}}function Ce(e,n,r,i,a){let o=i.get(e.name);if(!o){let n=Ee(e.name,i);throw new t(`Unknown flag --${e.name}${n?`. Did you mean --${n}?`:``}`,{code:`UNKNOWN_FLAG`,details:{flag:e.name,...n?{suggestion:n}:{}},...n?{suggest:`--${n}`}:{}})}let[s,c]=o;if(!j(c))return e.value===void 0?a[s]=!0:a[s]=M(s,e.value,c),r+1;if(e.value!==void 0)return F(a,s,c,e.value),r+1;let l=n[r+1];if(!l||l.kind!==`positional`)throw new t(`Flag --${s} requires a value`,{code:`MISSING_VALUE`,details:{flag:s,kind:c.kind}});return F(a,s,c,l.value),r+2}function we(e,n,r,i,a){let{chars:o}=e,s=r+1;for(let e=0;e<o.length;e++){let r=o.charAt(e),c=i.get(r);if(!c)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[l,u]=c;if(!j(u)){a[l]=!0;continue}if(e<o.length-1){F(a,l,u,o.slice(e+1));break}let d=n[s];if(!d||d.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:r,canonical:l,kind:u.kind}});F(a,l,u,d.value),s++}return s}function F(e,t,n,r){let i=M(t,r,n);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(i):e[t]=[i]}else e[t]=i}function Te(e,n){let r={},i=0;for(let t of e){if(t.schema.variadic){let e=n.slice(i);r[t.name]=e.map(e=>N(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=N(t.name,e,t.schema),i++)}if(i<n.length){let r=n.slice(i);throw new t(`Unexpected positional argument${r.length>1?`s`:``}: ${r.join(`, `)}`,{code:`UNEXPECTED_POSITIONAL`,details:{excess:r,expected:e.length}})}return r}function Ee(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){if(a.length<2)continue;let t=De(e,a);t<r&&t<=i&&(r=t,n=a)}return n}function De(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=n.length,a=r.length,o=Array.from({length:i+1},(e,t)=>t);for(let e=1;e<=a;e++){let t=o[0]??0;o[0]=e;for(let a=1;a<=i;a++){let i=n.charAt(a-1)===r.charAt(e-1)?0:1,s=Math.min((o[a]??0)+1,(o[a-1]??0)+1,t+i);t=o[a]??0,o[a]=s}}return o[i]??0}const I=Symbol.for(`dreamcli.prompt.cancel`);function L(e,t){let n=0;return{promptOne(){if(n>=e.length)return t?.onExhausted===`cancel`?Promise.resolve({answered:!1}):Promise.reject(Error(`Test prompter exhausted: expected at most ${e.length} prompts, got prompt #${n+1}`));let r=e[n];return n+=1,r===I?Promise.resolve({answered:!1}):Promise.resolve({answered:!0,value:r})}}}function Oe(e,t){return{promptOne(n){switch(n.kind){case`confirm`:return R(n,e,t);case`input`:return ke(n,e,t);case`select`:return Ae(n,e,t);case`multiselect`:return je(n,e,t)}}}}async function R(e,t,n){n(`${e.message} (y/n) `);let r=await t();if(r===null)return{answered:!1};let i=r.trim().toLowerCase();return i===``||i===`y`||i===`yes`?{answered:!0,value:!0}:i===`n`||i===`no`?{answered:!0,value:!1}:(n(`Please answer y or n.
|
|
10
|
+
`),R(e,t,n))}async function ke(e,t,n){let r=0;for(;r<10;){let i=e.placeholder===void 0?``:` (${e.placeholder})`;n(`${e.message}${i}: `);let a=await t();if(a===null)return{answered:!1};let o=a.trim();if(e.validate!==void 0){let t=e.validate(o);if(t!==!0){n(`${t}\n`),r+=1;continue}}return{answered:!0,value:o}}return n(`Too many invalid attempts.
|
|
11
|
+
`),{answered:!1}}async function Ae(e,t,n){let r=0;for(;r<10;){n(`${e.message}\n`);for(let t=0;t<e.choices.length;t+=1){let r=e.choices[t];if(r===void 0)continue;let i=r.label??r.value,a=r.description===void 0?``:` - ${r.description}`;n(` ${t+1}) ${i}${a}\n`)}n(`Enter number: `);let i=await t();if(i===null)return{answered:!1};let a=Number(i.trim());if(Number.isNaN(a)||!Number.isInteger(a)||a<1||a>e.choices.length){n(`Please enter a number between 1 and ${e.choices.length}.\n`),r+=1;continue}let o=e.choices[a-1];if(o===void 0){r+=1;continue}return{answered:!0,value:o.value}}return n(`Too many invalid attempts.
|
|
12
|
+
`),{answered:!1}}async function je(e,t,n){let r=0;for(;r<10;){n(`${e.message}\n`);for(let t=0;t<e.choices.length;t+=1){let r=e.choices[t];if(r===void 0)continue;let i=r.label??r.value,a=r.description===void 0?``:` - ${r.description}`;n(` ${t+1}) ${i}${a}\n`)}n(`Enter numbers separated by commas (e.g. 1,3${e.min===void 0?``:`, min: ${e.min}`}${e.max===void 0?``:`, max: ${e.max}`}): `);let i=await t();if(i===null)return{answered:!1};let a=i.trim();if(a===``){if(e.min!==void 0&&e.min>0){n(`Please select at least ${e.min}.\n`),r+=1;continue}return{answered:!0,value:[]}}let o=a.split(`,`).map(e=>e.trim()),s=[],c=!0;for(let t of o){let r=Number(t);if(Number.isNaN(r)||!Number.isInteger(r)||r<1||r>e.choices.length){n(`Invalid selection '${t}'. Use numbers between 1 and ${e.choices.length}.\n`),c=!1;break}s.push(r)}if(!c){r+=1;continue}let l=[...new Set(s)];if(e.min!==void 0&&l.length<e.min){n(`Please select at least ${e.min}.\n`),r+=1;continue}if(e.max!==void 0&&l.length>e.max){n(`Please select at most ${e.max}.\n`),r+=1;continue}return{answered:!0,value:l.map(t=>e.choices[t-1]?.value??``)}}return n(`Too many invalid attempts.
|
|
13
|
+
`),{answered:!1}}function z(e,t){if(e.kind===`confirm`||e.kind===`input`)return e;let n=e.choices??t?.map(e=>({value:e}))??[];if(n.length===0)throw Error(`Prompt config (${e.kind}) requires choices but none were provided and no enum values are available`);let r=n;return e.kind===`select`?{kind:`select`,message:e.message,choices:r}:{kind:`multiselect`,message:e.message,choices:r,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max}}}async function B(e,t,n){let r=n?.stdinData,i=n?.env??{},a=n?.config??{},o=n?.prompter,s=[];return{flags:await Me(e.flags,t.flags,i,a,o,e.interactive,s),args:Ie(e.args,t.args,r,i,s),deprecations:s}}async function Me(e,t,r,i,a,o,s){let c={},l=[],u=new Set;for(let[n,a]of Object.entries(e)){let e=t[n];if(e!==void 0){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=e;continue}if(a.envVar!==void 0){let e=r[a.envVar];if(e!==void 0){let t=W(n,{kind:`env`,envVar:a.envVar},e,a);if(t.ok){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=t.value;continue}l.push(t.error),u.add(n);continue}}if(a.configPath!==void 0){let e=Fe(i,a.configPath);if(e!==void 0){let t=W(n,{kind:`config`,configPath:a.configPath},e,a);if(t.ok){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=t.value;continue}l.push(t.error),u.add(n)}}}let d=o===void 0?void 0:o({flags:c});for(let[t,r]of Object.entries(e)){if(t in c||u.has(t))continue;let e=d?.[t],i;if(i=e!=null&&e!==!1&&e!==0&&e!==``?e:e===!1?void 0:r.prompt,i!==void 0&&a!==void 0){let e=await Ne(t,r,i,a);if(e.ok){r.deprecated!==void 0&&s.push({kind:`flag`,name:t,message:r.deprecated}),c[t]=e.value;continue}if(e.error!==void 0){l.push(e.error);continue}}if(r.defaultValue!==void 0){c[t]=r.defaultValue;continue}if(r.kind===`array`&&r.presence!==`required`){c[t]=[];continue}if(r.presence===`required`){let e={flag:t,kind:r.kind};r.envVar!==void 0&&(e.envVar=r.envVar),r.configPath!==void 0&&(e.configPath=r.configPath),l.push(new n(`Missing required flag --${t}`,{code:`REQUIRED_FLAG`,details:e,suggest:Pe(t,r)}));continue}c[t]=void 0}return Y(l)&&X(l),c}async function Ne(e,t,n,r){let i=z(n,t.enumValues),a=await r.promptOne(i);return a.answered?W(e,{kind:`prompt`},a.value,t):{ok:!1,error:void 0}}function Pe(e,t){let n=[];if(n.push(`Provide --${e}${t.kind===`boolean`?``:` <value>`}`),t.envVar!==void 0&&n.push(`set ${t.envVar}`),t.configPath!==void 0&&n.push(`add ${t.configPath} to config`),n.length<=1)return n.join(``);let r=n.slice(0,-1),i=n.slice(-1).join(``);return n.length===2?`${r.join(``)} or ${i}`:`${r.join(`, `)}, or ${i}`}function V(e){switch(e.kind){case`env`:return`from env ${e.envVar}`;case`config`:return`from config ${e.configPath}`;case`prompt`:return`from prompt`}}function H(e){switch(e.kind){case`env`:return{envVar:e.envVar};case`config`:return{configPath:e.configPath};case`prompt`:return{source:`prompt`}}}function U(e,t,r,i,a,o,s,c){return{ok:!1,error:new n(`${o} ${V(t)} for flag --${e}`,{code:r,details:{flag:e,...H(t),value:a,expected:i,...c},suggest:s})}}function W(e,t,r,i){switch(i.kind){case`string`:return typeof r==`string`?{ok:!0,value:r}:t.kind===`prompt`||t.kind===`config`&&(typeof r==`number`||typeof r==`boolean`)?{ok:!0,value:String(r)}:U(e,t,`TYPE_MISMATCH`,`string`,r,`Invalid string value`,t.kind===`config`?`Set ${t.configPath} to a string in your config`:`Enter a valid string for --${e}`);case`number`:if(typeof r==`number`)return Number.isNaN(r)?U(e,t,`TYPE_MISMATCH`,`number`,r,`Invalid number value NaN`,t.kind===`env`?`Set ${t.envVar} to a valid number`:t.kind===`config`?`Set ${t.configPath} to a valid number in your config`:`Enter a valid number for --${e}`):{ok:!0,value:r};if(typeof r==`string`){let e=Number(r);if(!Number.isNaN(e))return{ok:!0,value:e}}return U(e,t,`TYPE_MISMATCH`,`number`,r,typeof r==`string`?`Invalid number value '${r}'`:`Invalid number value`,t.kind===`env`?`Set ${t.envVar} to a valid number`:t.kind===`config`?`Set ${t.configPath} to a valid number in your config`:`Enter a valid number for --${e}`);case`boolean`:if(typeof r==`boolean`)return{ok:!0,value:r};if(typeof r==`string`){let e=r.toLowerCase();if(e===`true`||e===`1`||e===`yes`||t.kind===`prompt`&&e===`y`)return{ok:!0,value:!0};if(e===`false`||e===`0`||e===`no`||e===``||t.kind===`prompt`&&e===`n`)return{ok:!0,value:!1}}return U(e,t,`TYPE_MISMATCH`,`boolean`,r,typeof r==`string`?`Invalid boolean value '${r}'`:`Invalid boolean value`,t.kind===`env`?`Set ${t.envVar} to true/false, 1/0, or yes/no`:t.kind===`config`?`Set ${t.configPath} to true or false in your config`:`Answer yes or no for --${e}`);case`enum`:{let a=i.enumValues??[];return typeof r==`string`&&a.includes(r)?{ok:!0,value:r}:{ok:!1,error:new n(`Invalid value '${String(r)}' ${V(t)} for flag --${e}. Allowed: ${a.join(`, `)}`,{code:`INVALID_ENUM`,details:{flag:e,...H(t),value:r,allowed:a},suggest:t.kind===`env`?`Set ${t.envVar} to one of: ${a.join(`, `)}`:t.kind===`config`?`Set ${t.configPath} to one of: ${a.join(`, `)}`:`Select one of: ${a.join(`, `)}`})}}case`custom`:if(i.parseFn)try{return{ok:!0,value:i.parseFn(r)}}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,error:new n(`Failed to parse ${t.kind===`env`?`env ${t.envVar}`:t.kind===`config`?`config ${t.configPath}`:`prompt value`} for flag --${e}: ${a}`,{code:`TYPE_MISMATCH`,details:{flag:e,...H(t),value:r,expected:`custom`},suggest:t.kind===`env`?`Set ${t.envVar} to a valid value for --${e}`:t.kind===`config`?`Set ${t.configPath} to a valid value for --${e} in your config`:`Enter a valid value for --${e}`})}}return{ok:!0,value:r};case`array`:if(Array.isArray(r)){if(i.elementSchema){let n=[];for(let a of r){let r=W(e,t,a,i.elementSchema);if(!r.ok)return r;n.push(r.value)}return{ok:!0,value:n}}return{ok:!0,value:r}}if(typeof r==`string`){if(r===``)return{ok:!0,value:[]};let n=r.split(`,`);if(i.elementSchema){let r=[];for(let a of n){let n=W(e,t,t.kind===`prompt`?a.trim():a,i.elementSchema);if(!n.ok)return n;r.push(n.value)}return{ok:!0,value:r}}return{ok:!0,value:t.kind===`prompt`?n.map(e=>e.trim()):n}}return U(e,t,`TYPE_MISMATCH`,`array`,r,`Invalid array value`,t.kind===`env`?`Set ${t.envVar} to comma-separated values`:t.kind===`config`?`Set ${t.configPath} to an array in your config`:`Provide valid values for --${e}`)}}function Fe(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r||!Object.hasOwn(r,e))return;r=r[e]}return r}function Ie(e,t,r,i,a){let o={},s=[];for(let c of e){let{name:e,schema:l}=c,u=t[e];if(u!==void 0&&(!l.stdinMode||u!==`-`)&&!(l.variadic&&Array.isArray(u)&&u.length===0)){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=u;continue}if(l.stdinMode&&(u===void 0||u===`-`)&&r!=null){let t=q(e,{kind:`stdin`},r,l);if(t.ok){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=t.value;continue}s.push(t.error);continue}if(l.envVar!==void 0){let t=i[l.envVar];if(t!==void 0){let n=q(e,{kind:`env`,envVar:l.envVar},t,l);if(n.ok){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=n.value;continue}s.push(n.error);continue}}if(l.defaultValue!==void 0){o[e]=l.defaultValue;continue}if(l.variadic){if(l.presence===`required`){s.push(new n(`Missing required argument <${e}>`,{code:`REQUIRED_ARG`,details:{arg:e,variadic:!0},suggest:J(e,l,!0)}));continue}o[e]=[];continue}if(l.presence===`required`){s.push(new n(`Missing required argument <${e}>`,{code:`REQUIRED_ARG`,details:{arg:e},suggest:J(e,l)}));continue}o[e]=void 0}return Y(s)&&X(s),o}function G(e){return e.kind===`env`?`from env ${e.envVar}`:`from stdin`}function Le(e){return e.kind===`env`?{envVar:e.envVar}:{source:`stdin`}}function Re(e,t,n){return t.kind===`env`?n===`number`?`Set ${t.envVar} to a valid number`:`Set ${t.envVar} to a valid value for <${e}>`:n===`number`?`Pipe a valid number to stdin for <${e}>`:`Pipe a valid value to stdin for <${e}>`}function ze(e){return e.kind===`env`?{kind:`env`,envVar:e.envVar}:{kind:`prompt`}}function Be(e){let t={presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:e.description,prompt:void 0,deprecated:e.deprecated,propagate:!1,enumValues:void 0,elementSchema:void 0,parseFn:void 0};switch(e.kind){case`string`:return{...t,kind:`string`};case`number`:return{...t,kind:`number`};case`enum`:return{...t,kind:`enum`,enumValues:e.enumValues};case`custom`:{if(e.parseFn===void 0)return{...t,kind:`custom`,parseFn:void 0};let n=e.parseFn;return{...t,kind:`custom`,parseFn:e=>n(typeof e==`string`?e:String(e))}}default:return e.kind}}function Ve(e,t,n,r){switch(n.kind){case`number`:return`Invalid number value '<redacted>' ${G(t)} for argument <${e}>`;case`enum`:{let n=Array.isArray(r.details?.allowed)?r.details.allowed.filter(e=>typeof e==`string`):[];return`Invalid value '<redacted>' ${G(t)} for argument <${e}>. Allowed: ${n.join(`, `)}`}case`custom`:{let n=/: ([^:]+)$/.exec(r.message)?.[1];return n===void 0?`Invalid value '<redacted>' ${G(t)} for argument <${e}>`:`Invalid value '<redacted>' ${G(t)} for argument <${e}>: ${n}`}case`string`:return`Invalid value '<redacted>' ${G(t)} for argument <${e}>`;default:return n.kind}}function K(e,t,n,r){return{arg:e,...Le(t),...n.kind===`number`||n.kind===`custom`?{expected:n.kind}:{},...n.kind===`enum`&&Array.isArray(r.details?.allowed)?{allowed:r.details.allowed.filter(e=>typeof e==`string`)}:{}}}function He(e,t,n,r){if(n.kind===`number`||n.kind===`custom`)return Re(e,t,n.kind);if(n.kind===`enum`){let e=(Array.isArray(r.details?.allowed)?r.details.allowed.filter(e=>typeof e==`string`):[]).join(`, `);return t.kind===`env`?`Set ${t.envVar} to one of: ${e}`:`Provide one of: ${e}`}}function q(e,t,r,i){let a=W(e,ze(t),r,Be(i));if(a.ok)return a;let o=He(e,t,i,a.error),s=o===void 0?{code:a.error.code,details:K(e,t,i,a.error)}:{code:a.error.code,details:K(e,t,i,a.error),suggest:o};return{ok:!1,error:new n(Ve(e,t,i,a.error),s)}}function J(e,t,n){let r=[n?`Provide at least one value for <${e}>`:`Provide a value for <${e}>`];return t.stdinMode&&r.push(`pipe a value to stdin or pass '-'`),t.envVar!==void 0&&r.push(`set ${t.envVar}`),r.length===1?r[0]:r.length===2?`${r[0]} or ${r[1]}`:`${r.slice(0,-1).join(`, `)}, or ${r[r.length-1]}`}function Y(e){return e.length>0}function X(e){throw e.length===1?e[0]:new n(`Multiple validation errors:\n - ${e.map(e=>e.message).join(`
|
|
14
|
+
- `)}`,{code:e[0].code,details:{errors:e.map(e=>e.toJSON()),count:e.length},suggest:`Fix all missing required values listed above`})}async function Z(t,n,r){let i,a;if(r?.out!==void 0)i=r.out,a=r.captured??{stdout:[],stderr:[],activity:[]};else{let e={...r?.verbosity===void 0?{}:{verbosity:r.verbosity},...r?.jsonMode===void 0?{}:{jsonMode:r.jsonMode},...r?.isTTY===void 0?{}:{isTTY:r.isTTY}};[i,a]=O(Object.keys(e).length>0?e:void 0)}let o=r?.mergedSchema??t.schema,s=r?.meta??{name:o.name,bin:r?.help?.binName??o.name,version:void 0,command:o.name};if(n.includes(`--help`)||n.includes(`-h`)){let e=g(o,r?.help);return i.log(e),$(0,a,void 0)}if(!t.handler){let n=new e(`Command '${t.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${t.schema.name}' command`});return i.error(n.message),$(1,a,n)}try{await Ue(r?.plugins,{argv:n,command:o,meta:s,out:i});let e=P(o,n),c=r?.prompter??(r?.answers===void 0?void 0:L(r.answers)),l=await B(o,e,{...r?.stdinData===void 0?{}:{stdinData:r.stdinData},...r?.env===void 0?{}:{env:r.env},...r?.config===void 0?{}:{config:r.config},...c===void 0?{}:{prompter:c}}),u={args:l.args,flags:l.flags,deprecations:l.deprecations,command:o,meta:s,out:i};await Q(r?.plugins,`afterResolve`,u);for(let e of l.deprecations)i.warn(Ge(e));return await Q(r?.plugins,`beforeAction`,u),await We(t,l.flags,l.args,i,s),await Q(r?.plugins,`afterAction`,u),$(0,a,void 0)}catch(t){if(t instanceof e)return r?.jsonMode===!0?i.json({error:t.toJSON()}):(i.error(t.message),t.suggest!==void 0&&i.error(`Suggestion: ${t.suggest}`)),$(t.exitCode,a,t);let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return r?.jsonMode===!0?i.json({error:n.toJSON()}):i.error(n.message),$(1,a,n)}finally{i.stopActive()}}async function Ue(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function Q(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function We(t,n,r,i,a){let o=t._executionSteps,s=t.handler;if(s===void 0)throw new e(`Command '${t.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${t.schema.name}' command`});let c=async e=>{await s({flags:n,args:r,ctx:e,out:i,meta:a})};for(let t=o.length-1;t>=0;t--){let s=o[t];if(s===void 0)continue;let l=c;switch(s.kind){case`derive`:c=async t=>{let o=await s.handler({args:r,flags:n,ctx:t,out:i,meta:a});if(o===void 0){await l(t);return}if(typeof o!=`object`||!o||Array.isArray(o))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...o})};break;case`middleware`:c=async e=>{await s.handler({args:r,flags:n,ctx:e,out:i,meta:a,next:async t=>{await l({...e,...t})}})};break}}await c({})}function $(e,t,n){return{exitCode:e,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:n}}function Ge(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}export{i as _,L as a,k as c,g as d,h as f,r as g,n as h,Oe as i,O as l,t as m,B as n,z as o,e as p,I as r,P as s,Z as t,Se as u,a as v};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
var e=class extends Error{name=`CLIError`;code;exitCode;suggest;details;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.code=t.code,this.exitCode=t.exitCode??1,this.suggest=t.suggest,this.details=t.details}toJSON(){return{name:this.name,code:this.code,message:this.message,exitCode:this.exitCode,...this.suggest!==void 0&&{suggest:this.suggest},...this.details!==void 0&&{details:this.details}}}},t=class extends e{name=`ParseError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}},n=class extends e{name=`ValidationError`;constructor(e,t){super(e,{...t,exitCode:t.exitCode??2})}};function r(t){return t instanceof e}function i(e){return e instanceof t}function a(e){return e instanceof n}function o(e){if(e==null)return``;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return String(e);if(e instanceof Date)return Number.isNaN(e.getTime())?`Invalid Date`:e.toISOString();if(typeof e==`function`)return e.name.length>0?`[Function: ${e.name}]`:`[Function]`;try{return JSON.stringify(e)??`[unserializable]`}catch{return`[unserializable]`}}function s(e){return{width:e?.width??80,binName:e?.binName,isDefaultHelp:e?.isDefaultHelp??!1}}function c(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function l(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(`
|
|
2
|
+
`)}function u(e){return typeof e==`string`?`[deprecated: ${e}]`:`[deprecated]`}function d(e){return e===void 0?`undefined`:e===null?`null`:o(e)}function ee(e,t){let n=[],r=t.aliases.find(e=>e.length===1);return r!==void 0&&n.push(`-${r},`),n.push(`--${e}`),t.kind!==`boolean`&&n.push(f(t)),n.join(` `)}function f(e){switch(e.kind){case`string`:return`<string>`;case`number`:return`<number>`;case`enum`:return`<${(e.enumValues??[]).join(`|`)}>`;case`array`:return`<${e.elementSchema===void 0?`value`:f(e.elementSchema).slice(1,-1)}>...`;case`boolean`:return``;case`custom`:return`<value>`}}function p(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(u(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.configPath!==void 0&&t.push(`[config: ${e.configPath}]`),e.prompt!==void 0&&t.push(`[prompt]`),e.presence===`required`?t.push(`[required]`):e.presence===`defaulted`&&e.kind!==`boolean`&&t.push(`(default: ${d(e.defaultValue)})`),t.join(` `)}function te(e){let t=Object.keys(e);if(t.length===0)return[];let n=[...t].sort((t,n)=>{let r=e[t],i=e[n];if(r===void 0||i===void 0)return 0;let a=r.aliases.some(e=>e.length===1),o=i.aliases.some(e=>e.length===1);return a&&!o?-1:!a&&o?1:t.localeCompare(n)}),r=[];for(let t of n){let n=e[t];n!==void 0&&r.push({left:ee(t,n),description:p(n)})}return r}function m(e){let{name:t,schema:n}=e,r=n.kind===`enum`&&n.enumValues!==void 0?n.enumValues.join(`|`):t,i=n.variadic?`...`:``;return n.presence===`required`?`<${r}>${i}`:`[${r}]${i}`}function ne(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(u(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.presence===`defaulted`&&t.push(`(default: ${d(e.defaultValue)})`),t.join(` `)}function h(e,t){let n=s(t),r=[];r.push(re(e,n)),e.description!==void 0&&r.push(e.description);let i=e.commands.filter(e=>!e.hidden);return i.length>0&&r.push(oe(i,n)),e.args.length>0&&r.push(ie(e.args,n)),Object.keys(e.flags).length>0&&r.push(ae(e.flags,n)),e.examples.length>0&&r.push(se(e.examples)),r}function g(e,t){return`${h(e,t).join(`
|
|
3
|
+
|
|
4
|
+
`)}\n`}function re(e,t){let n=[`Usage:`],r=t.binName===void 0||t.isDefaultHelp&&t.binName===e.name?e.name:`${t.binName} ${e.name}`;n.push(r),e.commands.length>0&&n.push(`<command>`),Object.keys(e.flags).length>0&&n.push(`[flags]`);for(let t of e.args)n.push(m(t));return n.join(` `)}function ie(e,t){let n=[`Arguments:`],r=0,i=[];for(let t of e){let e=` ${m(t)}`,n=ne(t.schema);i.push({left:e,desc:n}),e.length>r&&(r=e.length)}let a=r+2;for(let{left:e,desc:r}of i)if(r.length===0)n.push(e);else{let i=c(e,a),o=l(r,t.width,a);n.push(`${i}${o}`)}return n.join(`
|
|
5
|
+
`)}function ae(e,t){let n=[`Flags:`],r=te(e);if(r.length===0)return``;let i=0;for(let e of r){let t=` ${e.left}`;t.length>i&&(i=t.length)}let a=i+2;for(let e of r){let r=` ${e.left}`;if(e.description.length===0)n.push(r);else{let i=c(r,a),o=l(e.description,t.width,a);n.push(`${i}${o}`)}}return n.join(`
|
|
6
|
+
`)}function oe(e,t){let n=[`Commands:`],r=0;for(let t of e)t.name.length>r&&(r=t.name.length);let i=2+r+2;for(let r of e){let e=` ${r.name}`,a=r.description??``;if(a.length===0)n.push(e);else{let r=c(e,i),o=l(a,t.width,i);n.push(`${r}${o}`)}}return n.join(`
|
|
7
|
+
`)}function se(e){let t=[`Examples:`];for(let n of e)n.description===void 0?t.push(` $ ${n.command}`):(t.push(` ${n.description}:`),t.push(` $ ${n.command}`));return t.join(`
|
|
8
|
+
`)}function _(e,t){e(`${t}\n`)}const ce={update(){},succeed(){},fail(){},stop(){},wrap(e){return e}},le={increment(){},update(){},done(){},fail(){}};var ue=class{stopped=!1;constructor(e,t){this.write=t,_(t,e)}update(e){}succeed(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}stop(){this.stopped||=!0}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},de=class{stopped=!1;constructor(e,t){this.write=t,e!==void 0&&_(t,e)}increment(e){}update(e){}done(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&_(this.write,e))}};const v=`\x1B[?25l`,y=`\x1B[?25h`,b=`\x1B[2K`,x=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];var S=class{stopped=!1;timer;frameIndex=0;text;constructor(e,t){this.write=t,this.text=e,t(v),this.render(),this.timer=setInterval(()=>{this.frameIndex=(this.frameIndex+1)%x.length,this.render()},80)}render(){let e=x[this.frameIndex]??x[0];this.write(`\r${b}${e} ${this.text}`)}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${b}${y}`)}update(e){this.stopped||(this.text=e,this.render())}succeed(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✗ ${e}`))}stop(){this.stopped||(this.stopped=!0,this.cleanup())}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},C=class{stopped=!1;timer;current=0;total;label;pulsePos=0;pulseDir=1;constructor(e,t){this.write=t,this.total=e.total,this.label=e.label??``,t(v),this.render(),this.total===void 0&&(this.timer=setInterval(()=>{this.advancePulse(),this.render()},80))}advancePulse(){this.pulsePos+=this.pulseDir,this.pulsePos+3>20?(this.pulseDir=-1,this.pulsePos=17):this.pulsePos<0&&(this.pulseDir=1,this.pulsePos=0)}render(){let e=this.total===void 0?this.renderIndeterminate():this.renderDeterminate(this.total),t=this.label.length>0?` ${this.label}`:``;this.write(`\r${b}${e}${t}`)}renderDeterminate(e){let t=e>0?Math.max(0,Math.min(this.current/e,1)):0,n=Math.round(t*20),r=20-n,i=Math.round(t*100);return`[${`█`.repeat(n)}${`░`.repeat(r)}] ${String(i)}%`}renderIndeterminate(){let e=``;for(let t=0;t<20;t++)e+=t>=this.pulsePos&&t<this.pulsePos+3?`█`:`░`;return`[${e}]`}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${b}${y}`)}increment(e){this.stopped||(this.current+=e??1,this.render())}update(e){this.stopped||(this.current=e,this.render())}done(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&_(this.write,`✗ ${e}`))}},fe=class{stopped=!1;constructor(e,t){this.events=t,t.push({type:`spinner:start`,text:e})}update(e){this.stopped||this.events.push({type:`spinner:update`,text:e})}succeed(e){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:succeed`,text:e??``}))}fail(e){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:fail`,text:e??``}))}stop(){this.stopped||(this.stopped=!0,this.events.push({type:`spinner:stop`}))}async wrap(e,t){try{let n=await e;return this.succeed(t?.succeed),n}catch(e){throw this.fail(t?.fail),e}}},pe=class{stopped=!1;constructor(e,t){this.events=t,t.push({type:`progress:start`,label:e.label??``,total:e.total})}increment(e){this.stopped||this.events.push({type:`progress:increment`,delta:e??1})}update(e){this.stopped||this.events.push({type:`progress:update`,value:e})}done(e){this.stopped||(this.stopped=!0,this.events.push({type:`progress:done`,text:e}))}fail(e){this.stopped||(this.stopped=!0,this.events.push({type:`progress:fail`,text:e}))}};const w=()=>{};function T(e){return{stdout:e?.stdout??w,stderr:e?.stderr??w,isTTY:e?.isTTY??!1,verbosity:e?.verbosity??`normal`,jsonMode:e?.jsonMode??!1}}var E=class{options;jsonMode;isTTY;constructor(e){this.options=e,this.jsonMode=e.jsonMode,this.isTTY=e.isTTY}log(e){_(this.options.jsonMode?this.options.stderr:this.options.stdout,e)}info(e){this.options.verbosity!==`quiet`&&_(this.options.jsonMode?this.options.stderr:this.options.stdout,e)}warn(e){_(this.options.stderr,e)}error(e){_(this.options.stderr,e)}json(e){_(this.options.stdout,JSON.stringify(e))}table(e,t,n){let{columns:r,options:i}=ge(t,n),a=ve(this.options.jsonMode,i),o=r??he(e);if(a===`json`){this.json(_e(e,o));return}let s=xe(e,o);s.length!==0&&_(ye(this.options,a,i),s)}activeCleanup;stopActive(){this.activeCleanup!==void 0&&(this.activeCleanup(),this.activeCleanup=void 0)}spinner(e,t){let n=t?.fallback??`silent`;if(this.options.jsonMode||!this.options.isTTY&&n===`silent`)return ce;if(this.stopActive(),this.options.isTTY){let t=new S(e,this.options.stderr);return this.activeCleanup=()=>t.stop(),t}let r=new ue(e,this.options.stderr);return this.activeCleanup=()=>r.stop(),r}progress(e){let t=e.fallback??`silent`;if(this.options.jsonMode||!this.options.isTTY&&t===`silent`)return le;if(this.stopActive(),this.options.isTTY){let t=new C(e,this.options.stderr);return this.activeCleanup=()=>t.done(),t}let n=new de(e.label,this.options.stderr);return this.activeCleanup=()=>n.done(),n}},me=class extends E{constructor(e,t){super(e),this.activity=t}spinner(e,t){return new fe(e,this.activity)}progress(e){return new pe(e,this.activity)}};function he(e){let t=e[0];return t===void 0?[]:Object.keys(t).map(e=>({key:e}))}function D(e){return Array.isArray(e)}function ge(e,t){return t===void 0?D(e)?{columns:e,options:t}:{columns:void 0,options:e}:{columns:D(e)?e:void 0,options:t}}function _e(e,t){return e.map(e=>Object.fromEntries(t.map(t=>[t.key,e[t.key]])))}function ve(e,t){switch(t?.format){case`json`:return`json`;case`text`:return`text`;case`auto`:case void 0:return e?`json`:`text`}}function ye(e,t,n){return t===`text`&&n!==void 0&&`stream`in n&&n.stream!==void 0?n.stream===`stderr`?e.stderr:e.stdout:e.jsonMode?e.stderr:e.stdout}function be(e){return o(e)}function xe(e,t){if(e.length===0||t.length===0)return``;let n=t.map(e=>e.header??e.key),r=e.map(e=>t.map(t=>be(e[t.key]))),i=n.map((e,t)=>{let n=e.length;for(let e of r){let r=e[t];r!==void 0&&r.length>n&&(n=r.length)}return n});return[n.map((e,t)=>e.padEnd(i[t]??0)).join(` `),i.map(e=>`-`.repeat(e)).join(` `),...r.map(e=>e.map((e,t)=>e.padEnd(i[t]??0)).join(` `))].join(`
|
|
9
|
+
`)}function Se(e){return new E(T(e))}function O(e){let t={stdout:[],stderr:[],activity:[]};return[new me(T({...e,stdout:e=>t.stdout.push(e),stderr:e=>t.stderr.push(e)}),t.activity),t]}function k(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function A(e){let t=new Map;for(let[n,r]of Object.entries(e)){t.set(n,[n,r]);for(let e of r.aliases)t.set(e,[n,r])}return t}function j(e){return e.kind!==`boolean`}function M(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for flag --${e}`,{code:`INVALID_VALUE`,details:{flag:e,value:n,expected:`number`}});return r}case`boolean`:if(n===`true`||n===`1`)return!0;if(n===`false`||n===`0`)return!1;throw new t(`Invalid boolean value '${n}' for flag --${e}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,value:n,expected:`boolean`}});case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum flag --${e} is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{flag:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for flag --${e}. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,value:n,allowed:i}});return n}case`array`:return r.elementSchema?M(e,n,r.elementSchema):n;case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse flag --${e}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,value:n},cause:r})}}}function N(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for argument <${e}>`,{code:`INVALID_VALUE`,details:{arg:e,value:n,expected:`number`}});return r}case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum argument <${e}> is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{arg:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for argument <${e}>. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n,allowed:i}});return n}case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse argument <${e}>: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n},cause:r})}}}function P(e,t){let n=k(t),r=A(e.flags),i={},a=[],o=0;for(;o<n.length;){let e=n[o];if(e===void 0)break;if(e.kind===`separator`){o++;continue}if(e.kind===`positional`){a.push(e.value),o++;continue}if(e.kind===`long-flag`){o=Ce(e,n,o,r,i);continue}o=we(e,n,o,r,i)}return{flags:i,args:Te(e.args,a)}}function Ce(e,n,r,i,a){let o=i.get(e.name);if(!o){let n=Ee(e.name,i);throw new t(`Unknown flag --${e.name}${n?`. Did you mean --${n}?`:``}`,{code:`UNKNOWN_FLAG`,details:{flag:e.name,...n?{suggestion:n}:{}},...n?{suggest:`--${n}`}:{}})}let[s,c]=o;if(!j(c))return e.value===void 0?a[s]=!0:a[s]=M(s,e.value,c),r+1;if(e.value!==void 0)return F(a,s,c,e.value),r+1;let l=n[r+1];if(!l||l.kind!==`positional`)throw new t(`Flag --${s} requires a value`,{code:`MISSING_VALUE`,details:{flag:s,kind:c.kind}});return F(a,s,c,l.value),r+2}function we(e,n,r,i,a){let{chars:o}=e,s=r+1;for(let e=0;e<o.length;e++){let r=o.charAt(e),c=i.get(r);if(!c)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[l,u]=c;if(!j(u)){a[l]=!0;continue}if(e<o.length-1){F(a,l,u,o.slice(e+1));break}let d=n[s];if(!d||d.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:r,canonical:l,kind:u.kind}});F(a,l,u,d.value),s++}return s}function F(e,t,n,r){let i=M(t,r,n);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(i):e[t]=[i]}else e[t]=i}function Te(e,n){let r={},i=0;for(let t of e){if(t.schema.variadic){let e=n.slice(i);r[t.name]=e.map(e=>N(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=N(t.name,e,t.schema),i++)}if(i<n.length){let r=n.slice(i);throw new t(`Unexpected positional argument${r.length>1?`s`:``}: ${r.join(`, `)}`,{code:`UNEXPECTED_POSITIONAL`,details:{excess:r,expected:e.length}})}return r}function Ee(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){if(a.length<2)continue;let t=De(e,a);t<r&&t<=i&&(r=t,n=a)}return n}function De(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=n.length,a=r.length,o=Array.from({length:i+1},(e,t)=>t);for(let e=1;e<=a;e++){let t=o[0]??0;o[0]=e;for(let a=1;a<=i;a++){let i=n.charAt(a-1)===r.charAt(e-1)?0:1,s=Math.min((o[a]??0)+1,(o[a-1]??0)+1,t+i);t=o[a]??0,o[a]=s}}return o[i]??0}const I=Symbol.for(`dreamcli.prompt.cancel`);function L(e,t){let n=0;return{promptOne(){if(n>=e.length)return t?.onExhausted===`cancel`?Promise.resolve({answered:!1}):Promise.reject(Error(`Test prompter exhausted: expected at most ${e.length} prompts, got prompt #${n+1}`));let r=e[n];return n+=1,r===I?Promise.resolve({answered:!1}):Promise.resolve({answered:!0,value:r})}}}function Oe(e,t){return{promptOne(n){switch(n.kind){case`confirm`:return R(n,e,t);case`input`:return ke(n,e,t);case`select`:return Ae(n,e,t);case`multiselect`:return je(n,e,t)}}}}async function R(e,t,n){n(`${e.message} (y/n) `);let r=await t();if(r===null)return{answered:!1};let i=r.trim().toLowerCase();return i===``||i===`y`||i===`yes`?{answered:!0,value:!0}:i===`n`||i===`no`?{answered:!0,value:!1}:(n(`Please answer y or n.
|
|
10
|
+
`),R(e,t,n))}async function ke(e,t,n){let r=0;for(;r<10;){let i=e.placeholder===void 0?``:` (${e.placeholder})`;n(`${e.message}${i}: `);let a=await t();if(a===null)return{answered:!1};let o=a.trim();if(e.validate!==void 0){let t=e.validate(o);if(t!==!0){n(`${t}\n`),r+=1;continue}}return{answered:!0,value:o}}return n(`Too many invalid attempts.
|
|
11
|
+
`),{answered:!1}}async function Ae(e,t,n){let r=0;for(;r<10;){n(`${e.message}\n`);for(let t=0;t<e.choices.length;t+=1){let r=e.choices[t];if(r===void 0)continue;let i=r.label??r.value,a=r.description===void 0?``:` - ${r.description}`;n(` ${t+1}) ${i}${a}\n`)}n(`Enter number: `);let i=await t();if(i===null)return{answered:!1};let a=Number(i.trim());if(Number.isNaN(a)||!Number.isInteger(a)||a<1||a>e.choices.length){n(`Please enter a number between 1 and ${e.choices.length}.\n`),r+=1;continue}let o=e.choices[a-1];if(o===void 0){r+=1;continue}return{answered:!0,value:o.value}}return n(`Too many invalid attempts.
|
|
12
|
+
`),{answered:!1}}async function je(e,t,n){let r=0;for(;r<10;){n(`${e.message}\n`);for(let t=0;t<e.choices.length;t+=1){let r=e.choices[t];if(r===void 0)continue;let i=r.label??r.value,a=r.description===void 0?``:` - ${r.description}`;n(` ${t+1}) ${i}${a}\n`)}n(`Enter numbers separated by commas (e.g. 1,3${e.min===void 0?``:`, min: ${e.min}`}${e.max===void 0?``:`, max: ${e.max}`}): `);let i=await t();if(i===null)return{answered:!1};let a=i.trim();if(a===``){if(e.min!==void 0&&e.min>0){n(`Please select at least ${e.min}.\n`),r+=1;continue}return{answered:!0,value:[]}}let o=a.split(`,`).map(e=>e.trim()),s=[],c=!0;for(let t of o){let r=Number(t);if(Number.isNaN(r)||!Number.isInteger(r)||r<1||r>e.choices.length){n(`Invalid selection '${t}'. Use numbers between 1 and ${e.choices.length}.\n`),c=!1;break}s.push(r)}if(!c){r+=1;continue}let l=[...new Set(s)];if(e.min!==void 0&&l.length<e.min){n(`Please select at least ${e.min}.\n`),r+=1;continue}if(e.max!==void 0&&l.length>e.max){n(`Please select at most ${e.max}.\n`),r+=1;continue}return{answered:!0,value:l.map(t=>e.choices[t-1]?.value??``)}}return n(`Too many invalid attempts.
|
|
13
|
+
`),{answered:!1}}function z(e,t){if(e.kind===`confirm`||e.kind===`input`)return e;let n=e.choices??t?.map(e=>({value:e}))??[];if(n.length===0)throw Error(`Prompt config (${e.kind}) requires choices but none were provided and no enum values are available`);let r=n;return e.kind===`select`?{kind:`select`,message:e.message,choices:r}:{kind:`multiselect`,message:e.message,choices:r,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max}}}async function B(e,t,n){let r=n?.stdinData,i=n?.env??{},a=n?.config??{},o=n?.prompter,s=[];return{flags:await Me(e.flags,t.flags,i,a,o,e.interactive,s),args:Ie(e.args,t.args,r,i,s),deprecations:s}}async function Me(e,t,r,i,a,o,s){let c={},l=[],u=new Set;for(let[n,a]of Object.entries(e)){let e=t[n];if(e!==void 0){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=e;continue}if(a.envVar!==void 0){let e=r[a.envVar];if(e!==void 0){let t=W(n,{kind:`env`,envVar:a.envVar},e,a);if(t.ok){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=t.value;continue}l.push(t.error),u.add(n);continue}}if(a.configPath!==void 0){let e=Fe(i,a.configPath);if(e!==void 0){let t=W(n,{kind:`config`,configPath:a.configPath},e,a);if(t.ok){a.deprecated!==void 0&&s.push({kind:`flag`,name:n,message:a.deprecated}),c[n]=t.value;continue}l.push(t.error),u.add(n)}}}let d=o===void 0?void 0:o({flags:c});for(let[t,r]of Object.entries(e)){if(t in c||u.has(t))continue;let e=d?.[t],i;if(i=e!=null&&e!==!1&&e!==0&&e!==``?e:e===!1?void 0:r.prompt,i!==void 0&&a!==void 0){let e=await Ne(t,r,i,a);if(e.ok){r.deprecated!==void 0&&s.push({kind:`flag`,name:t,message:r.deprecated}),c[t]=e.value;continue}if(e.error!==void 0){l.push(e.error);continue}}if(r.defaultValue!==void 0){c[t]=r.defaultValue;continue}if(r.kind===`array`&&r.presence!==`required`){c[t]=[];continue}if(r.presence===`required`){let e={flag:t,kind:r.kind};r.envVar!==void 0&&(e.envVar=r.envVar),r.configPath!==void 0&&(e.configPath=r.configPath),l.push(new n(`Missing required flag --${t}`,{code:`REQUIRED_FLAG`,details:e,suggest:Pe(t,r)}));continue}c[t]=void 0}return Y(l)&&X(l),c}async function Ne(e,t,n,r){let i=z(n,t.enumValues),a=await r.promptOne(i);return a.answered?W(e,{kind:`prompt`},a.value,t):{ok:!1,error:void 0}}function Pe(e,t){let n=[];if(n.push(`Provide --${e}${t.kind===`boolean`?``:` <value>`}`),t.envVar!==void 0&&n.push(`set ${t.envVar}`),t.configPath!==void 0&&n.push(`add ${t.configPath} to config`),n.length<=1)return n.join(``);let r=n.slice(0,-1),i=n.slice(-1).join(``);return n.length===2?`${r.join(``)} or ${i}`:`${r.join(`, `)}, or ${i}`}function V(e){switch(e.kind){case`env`:return`from env ${e.envVar}`;case`config`:return`from config ${e.configPath}`;case`prompt`:return`from prompt`}}function H(e){switch(e.kind){case`env`:return{envVar:e.envVar};case`config`:return{configPath:e.configPath};case`prompt`:return{source:`prompt`}}}function U(e,t,r,i,a,o,s,c){return{ok:!1,error:new n(`${o} ${V(t)} for flag --${e}`,{code:r,details:{flag:e,...H(t),value:a,expected:i,...c},suggest:s})}}function W(e,t,r,i){switch(i.kind){case`string`:return typeof r==`string`?{ok:!0,value:r}:t.kind===`prompt`||t.kind===`config`&&(typeof r==`number`||typeof r==`boolean`)?{ok:!0,value:String(r)}:U(e,t,`TYPE_MISMATCH`,`string`,r,`Invalid string value`,t.kind===`config`?`Set ${t.configPath} to a string in your config`:`Enter a valid string for --${e}`);case`number`:if(typeof r==`number`)return Number.isNaN(r)?U(e,t,`TYPE_MISMATCH`,`number`,r,`Invalid number value NaN`,t.kind===`env`?`Set ${t.envVar} to a valid number`:t.kind===`config`?`Set ${t.configPath} to a valid number in your config`:`Enter a valid number for --${e}`):{ok:!0,value:r};if(typeof r==`string`){let e=Number(r);if(!Number.isNaN(e))return{ok:!0,value:e}}return U(e,t,`TYPE_MISMATCH`,`number`,r,typeof r==`string`?`Invalid number value '${r}'`:`Invalid number value`,t.kind===`env`?`Set ${t.envVar} to a valid number`:t.kind===`config`?`Set ${t.configPath} to a valid number in your config`:`Enter a valid number for --${e}`);case`boolean`:if(typeof r==`boolean`)return{ok:!0,value:r};if(typeof r==`string`){let e=r.toLowerCase();if(e===`true`||e===`1`||e===`yes`||t.kind===`prompt`&&e===`y`)return{ok:!0,value:!0};if(e===`false`||e===`0`||e===`no`||e===``||t.kind===`prompt`&&e===`n`)return{ok:!0,value:!1}}return U(e,t,`TYPE_MISMATCH`,`boolean`,r,typeof r==`string`?`Invalid boolean value '${r}'`:`Invalid boolean value`,t.kind===`env`?`Set ${t.envVar} to true/false, 1/0, or yes/no`:t.kind===`config`?`Set ${t.configPath} to true or false in your config`:`Answer yes or no for --${e}`);case`enum`:{let a=i.enumValues??[];return typeof r==`string`&&a.includes(r)?{ok:!0,value:r}:{ok:!1,error:new n(`Invalid value '${String(r)}' ${V(t)} for flag --${e}. Allowed: ${a.join(`, `)}`,{code:`INVALID_ENUM`,details:{flag:e,...H(t),value:r,allowed:a},suggest:t.kind===`env`?`Set ${t.envVar} to one of: ${a.join(`, `)}`:t.kind===`config`?`Set ${t.configPath} to one of: ${a.join(`, `)}`:`Select one of: ${a.join(`, `)}`})}}case`custom`:if(i.parseFn)try{return{ok:!0,value:i.parseFn(r)}}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,error:new n(`Failed to parse ${t.kind===`env`?`env ${t.envVar}`:t.kind===`config`?`config ${t.configPath}`:`prompt value`} for flag --${e}: ${a}`,{code:`TYPE_MISMATCH`,details:{flag:e,...H(t),value:r,expected:`custom`},suggest:t.kind===`env`?`Set ${t.envVar} to a valid value for --${e}`:t.kind===`config`?`Set ${t.configPath} to a valid value for --${e} in your config`:`Enter a valid value for --${e}`})}}return{ok:!0,value:r};case`array`:if(Array.isArray(r)){if(i.elementSchema){let n=[];for(let a of r){let r=W(e,t,a,i.elementSchema);if(!r.ok)return r;n.push(r.value)}return{ok:!0,value:n}}return{ok:!0,value:r}}if(typeof r==`string`){if(r===``)return{ok:!0,value:[]};let n=r.split(`,`);if(i.elementSchema){let r=[];for(let a of n){let n=W(e,t,t.kind===`prompt`?a.trim():a,i.elementSchema);if(!n.ok)return n;r.push(n.value)}return{ok:!0,value:r}}return{ok:!0,value:t.kind===`prompt`?n.map(e=>e.trim()):n}}return U(e,t,`TYPE_MISMATCH`,`array`,r,`Invalid array value`,t.kind===`env`?`Set ${t.envVar} to comma-separated values`:t.kind===`config`?`Set ${t.configPath} to an array in your config`:`Provide valid values for --${e}`)}}function Fe(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r||!Object.hasOwn(r,e))return;r=r[e]}return r}function Ie(e,t,r,i,a){let o={},s=[];for(let c of e){let{name:e,schema:l}=c,u=t[e];if(u!==void 0&&(!l.stdinMode||u!==`-`)&&!(l.variadic&&Array.isArray(u)&&u.length===0)){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=u;continue}if(l.stdinMode&&(u===void 0||u===`-`)&&r!=null){let t=q(e,{kind:`stdin`},r,l);if(t.ok){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=t.value;continue}s.push(t.error);continue}if(l.envVar!==void 0){let t=i[l.envVar];if(t!==void 0){let n=q(e,{kind:`env`,envVar:l.envVar},t,l);if(n.ok){l.deprecated!==void 0&&a.push({kind:`arg`,name:e,message:l.deprecated}),o[e]=n.value;continue}s.push(n.error);continue}}if(l.defaultValue!==void 0){o[e]=l.defaultValue;continue}if(l.variadic){if(l.presence===`required`){s.push(new n(`Missing required argument <${e}>`,{code:`REQUIRED_ARG`,details:{arg:e,variadic:!0},suggest:J(e,l,!0)}));continue}o[e]=[];continue}if(l.presence===`required`){s.push(new n(`Missing required argument <${e}>`,{code:`REQUIRED_ARG`,details:{arg:e},suggest:J(e,l)}));continue}o[e]=void 0}return Y(s)&&X(s),o}function G(e){return e.kind===`env`?`from env ${e.envVar}`:`from stdin`}function Le(e){return e.kind===`env`?{envVar:e.envVar}:{source:`stdin`}}function Re(e,t,n){return t.kind===`env`?n===`number`?`Set ${t.envVar} to a valid number`:`Set ${t.envVar} to a valid value for <${e}>`:n===`number`?`Pipe a valid number to stdin for <${e}>`:`Pipe a valid value to stdin for <${e}>`}function ze(e){return e.kind===`env`?{kind:`env`,envVar:e.envVar}:{kind:`prompt`}}function Be(e){let t={presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:e.description,prompt:void 0,deprecated:e.deprecated,propagate:!1,enumValues:void 0,elementSchema:void 0,parseFn:void 0};switch(e.kind){case`string`:return{...t,kind:`string`};case`number`:return{...t,kind:`number`};case`enum`:return{...t,kind:`enum`,enumValues:e.enumValues};case`custom`:{if(e.parseFn===void 0)return{...t,kind:`custom`,parseFn:void 0};let n=e.parseFn;return{...t,kind:`custom`,parseFn:e=>n(typeof e==`string`?e:String(e))}}default:return e.kind}}function Ve(e,t,n,r){switch(n.kind){case`number`:return`Invalid number value '<redacted>' ${G(t)} for argument <${e}>`;case`enum`:{let n=Array.isArray(r.details?.allowed)?r.details.allowed.filter(e=>typeof e==`string`):[];return`Invalid value '<redacted>' ${G(t)} for argument <${e}>. Allowed: ${n.join(`, `)}`}case`custom`:{let n=/: ([^:]+)$/.exec(r.message)?.[1];return n===void 0?`Invalid value '<redacted>' ${G(t)} for argument <${e}>`:`Invalid value '<redacted>' ${G(t)} for argument <${e}>: ${n}`}case`string`:return`Invalid value '<redacted>' ${G(t)} for argument <${e}>`;default:return n.kind}}function K(e,t,n,r){return{arg:e,...Le(t),...n.kind===`number`||n.kind===`custom`?{expected:n.kind}:{},...n.kind===`enum`&&Array.isArray(r.details?.allowed)?{allowed:r.details.allowed.filter(e=>typeof e==`string`)}:{}}}function He(e,t,n,r){if(n.kind===`number`||n.kind===`custom`)return Re(e,t,n.kind);if(n.kind===`enum`){let e=(Array.isArray(r.details?.allowed)?r.details.allowed.filter(e=>typeof e==`string`):[]).join(`, `);return t.kind===`env`?`Set ${t.envVar} to one of: ${e}`:`Provide one of: ${e}`}}function q(e,t,r,i){let a=W(e,ze(t),r,Be(i));if(a.ok)return a;let o=He(e,t,i,a.error),s=o===void 0?{code:a.error.code,details:K(e,t,i,a.error)}:{code:a.error.code,details:K(e,t,i,a.error),suggest:o};return{ok:!1,error:new n(Ve(e,t,i,a.error),s)}}function J(e,t,n){let r=[n?`Provide at least one value for <${e}>`:`Provide a value for <${e}>`];return t.stdinMode&&r.push(`pipe a value to stdin or pass '-'`),t.envVar!==void 0&&r.push(`set ${t.envVar}`),r.length===1?r[0]:r.length===2?`${r[0]} or ${r[1]}`:`${r.slice(0,-1).join(`, `)}, or ${r[r.length-1]}`}function Y(e){return e.length>0}function X(e){throw e.length===1?e[0]:new n(`Multiple validation errors:\n - ${e.map(e=>e.message).join(`
|
|
14
|
+
- `)}`,{code:e[0].code,details:{errors:e.map(e=>e.toJSON()),count:e.length},suggest:`Fix all missing required values listed above`})}async function Z(t,n,r){let i,a;if(r?.out!==void 0)i=r.out,a=r.captured??{stdout:[],stderr:[],activity:[]};else{let e={...r?.verbosity===void 0?{}:{verbosity:r.verbosity},...r?.jsonMode===void 0?{}:{jsonMode:r.jsonMode},...r?.isTTY===void 0?{}:{isTTY:r.isTTY}};[i,a]=O(Object.keys(e).length>0?e:void 0)}let o=r?.mergedSchema??t.schema,s=r?.meta??{name:o.name,bin:r?.help?.binName??o.name,version:void 0,command:o.name};if(n.includes(`--help`)||n.includes(`-h`)){let e=g(o,r?.help);return i.log(e),$(0,a,void 0)}if(!t.handler){let n=new e(`Command '${t.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${t.schema.name}' command`});return i.error(n.message),$(1,a,n)}try{await Ue(r?.plugins,{argv:n,command:o,meta:s,out:i});let e=P(o,n),c=r?.prompter??(r?.answers===void 0?void 0:L(r.answers)),l=await B(o,e,{...r?.stdinData===void 0?{}:{stdinData:r.stdinData},...r?.env===void 0?{}:{env:r.env},...r?.config===void 0?{}:{config:r.config},...c===void 0?{}:{prompter:c}}),u={args:l.args,flags:l.flags,deprecations:l.deprecations,command:o,meta:s,out:i};await Q(r?.plugins,`afterResolve`,u);for(let e of l.deprecations)i.warn(Ge(e));return await Q(r?.plugins,`beforeAction`,u),await We(t,l.flags,l.args,i,s),await Q(r?.plugins,`afterAction`,u),$(0,a,void 0)}catch(t){if(t instanceof e)return r?.jsonMode===!0?i.json({error:t.toJSON()}):(i.error(t.message),t.suggest!==void 0&&i.error(`Suggestion: ${t.suggest}`)),$(t.exitCode,a,t);let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return r?.jsonMode===!0?i.json({error:n.toJSON()}):i.error(n.message),$(1,a,n)}finally{i.stopActive()}}async function Ue(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function Q(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function We(t,n,r,i,a){let o=t._executionSteps,s=t.handler;if(s===void 0)throw new e(`Command '${t.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${t.schema.name}' command`});let c=async e=>{await s({flags:n,args:r,ctx:e,out:i,meta:a})};for(let t=o.length-1;t>=0;t--){let s=o[t];if(s===void 0)continue;let l=c;switch(s.kind){case`derive`:c=async t=>{let o=await s.handler({args:r,flags:n,ctx:t,out:i,meta:a});if(o===void 0){await l(t);return}if(typeof o!=`object`||!o||Array.isArray(o))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...o})};break;case`middleware`:c=async e=>{await s.handler({args:r,flags:n,ctx:e,out:i,meta:a,next:async t=>{await l({...e,...t})}})};break}}await c({})}function $(e,t,n){return{exitCode:e,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:n}}function Ge(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return a}});
|
package/dist/testkit.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./testkit-ClIKijxC.cjs`),t=require(`./adapter-CCSh5juX.cjs`);exports.PROMPT_CANCEL=e.r,exports.createCaptureOutput=e.l,exports.createTestAdapter=t.n,exports.createTestPrompter=e.a,exports.runCommand=e.t;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { C as RunOptions, St as FlagConfig, Ut as ArgBuilder, Wt as ArgConfig, X as PROMPT_CANCEL, at as createTestPrompter, i as createTestAdapter, l as CommandBuilder, nt as TestAnswer, r as TestAdapterOptions, rt as TestPrompterOptions, st as CapturedOutput, ut as createCaptureOutput, w as RunResult, xt as FlagBuilder } from "./adapter-DQnxxLiE.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/testkit/index.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Run a command builder against the given argv with injected options.
|
|
6
|
+
*
|
|
7
|
+
* This is the core execution pipeline:
|
|
8
|
+
* 1. Detect `--help` / `-h` → print help text, exit 0
|
|
9
|
+
* 2. Parse argv against the command schema
|
|
10
|
+
* 3. Resolve values (CLI → env → config → default)
|
|
11
|
+
* 4. Create a capture output channel
|
|
12
|
+
* 5. Run derive/middleware/action execution steps
|
|
13
|
+
* 6. Return structured result
|
|
14
|
+
*
|
|
15
|
+
* All errors are caught and converted to structured `RunResult`s with
|
|
16
|
+
* appropriate exit codes. The function never throws.
|
|
17
|
+
*
|
|
18
|
+
* @param cmd - The command builder (must have an action handler)
|
|
19
|
+
* @param argv - Raw argv strings (NOT including the command name itself)
|
|
20
|
+
* @param options - Injectable runtime state
|
|
21
|
+
* @returns Structured run result with exit code and captured output
|
|
22
|
+
*/
|
|
23
|
+
declare function runCommand<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>>(cmd: CommandBuilder<F, A, C>, argv: readonly string[], options?: RunOptions): Promise<RunResult>;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { type CapturedOutput, PROMPT_CANCEL, type RunOptions, type RunResult, type TestAdapterOptions, type TestAnswer, type TestPrompterOptions, createCaptureOutput, createTestAdapter, createTestPrompter, runCommand };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { C as RunOptions, St as FlagConfig, Ut as ArgBuilder, Wt as ArgConfig, X as PROMPT_CANCEL, at as createTestPrompter, i as createTestAdapter, l as CommandBuilder, nt as TestAnswer, r as TestAdapterOptions, rt as TestPrompterOptions, st as CapturedOutput, ut as createCaptureOutput, w as RunResult, xt as FlagBuilder } from "./adapter-DIwO-q7K.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/testkit/index.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Run a command builder against the given argv with injected options.
|
|
6
|
+
*
|
|
7
|
+
* This is the core execution pipeline:
|
|
8
|
+
* 1. Detect `--help` / `-h` → print help text, exit 0
|
|
9
|
+
* 2. Parse argv against the command schema
|
|
10
|
+
* 3. Resolve values (CLI → env → config → default)
|
|
11
|
+
* 4. Create a capture output channel
|
|
12
|
+
* 5. Run derive/middleware/action execution steps
|
|
13
|
+
* 6. Return structured result
|
|
14
|
+
*
|
|
15
|
+
* All errors are caught and converted to structured `RunResult`s with
|
|
16
|
+
* appropriate exit codes. The function never throws.
|
|
17
|
+
*
|
|
18
|
+
* @param cmd - The command builder (must have an action handler)
|
|
19
|
+
* @param argv - Raw argv strings (NOT including the command name itself)
|
|
20
|
+
* @param options - Injectable runtime state
|
|
21
|
+
* @returns Structured run result with exit code and captured output
|
|
22
|
+
*/
|
|
23
|
+
declare function runCommand<F extends Record<string, FlagBuilder<FlagConfig>>, A extends Record<string, ArgBuilder<ArgConfig>>, C extends Record<string, unknown> = Record<string, never>>(cmd: CommandBuilder<F, A, C>, argv: readonly string[], options?: RunOptions): Promise<RunResult>;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { type CapturedOutput, PROMPT_CANCEL, type RunOptions, type RunResult, type TestAdapterOptions, type TestAnswer, type TestPrompterOptions, createCaptureOutput, createTestAdapter, createTestPrompter, runCommand };
|
package/dist/testkit.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,l as t,r as n,t as r}from"./testkit-CEDYPvhF.mjs";import{n as i}from"./adapter-B37d9oia.mjs";export{n as PROMPT_CANCEL,t as createCaptureOutput,i as createTestAdapter,e as createTestPrompter,r as runCommand};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Basic single-command CLI.
|
|
4
|
+
*
|
|
5
|
+
* Demonstrates: positional args, typed flags, default values, aliases.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* npx tsx examples/basic.ts Alice
|
|
9
|
+
* npx tsx examples/basic.ts Alice --loud --times 3
|
|
10
|
+
* npx tsx examples/basic.ts Alice -l -t 3
|
|
11
|
+
* npx tsx examples/basic.ts --help
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { arg, cli, command, flag } from 'dreamcli';
|
|
15
|
+
|
|
16
|
+
const greet = command('greet')
|
|
17
|
+
.description('Greet someone')
|
|
18
|
+
.example('greet Alice', 'Greet Alice once')
|
|
19
|
+
.example('greet Alice --loud --times 3', 'Shout the greeting three times')
|
|
20
|
+
.arg('name', arg.string().describe('Who to greet'))
|
|
21
|
+
.flag('loud', flag.boolean().alias('l').describe('Shout the greeting'))
|
|
22
|
+
.flag('times', flag.number().default(1).alias('t').describe('Repeat count'))
|
|
23
|
+
.action(({ args, flags, out }) => {
|
|
24
|
+
// args.name: string — required positional
|
|
25
|
+
// flags.loud: boolean — defaults to false (all booleans do)
|
|
26
|
+
// flags.times: number — defaults to 1 (never undefined)
|
|
27
|
+
for (let i = 0; i < flags.times; i++) {
|
|
28
|
+
const msg = `Hello, ${args.name}!`;
|
|
29
|
+
out.log(flags.loud ? msg.toUpperCase() : msg);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
void cli('greet').default(greet).run();
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "gh",
|
|
3
|
+
"version": "0.0.0-example",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "A minimal GitHub CLI clone — dreamcli walkthrough example",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/kjanat/dreamcli.git",
|
|
9
|
+
"directory": "examples/gh"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"module": "src/main.ts",
|
|
13
|
+
"bin": {
|
|
14
|
+
"gh": "src/main.ts",
|
|
15
|
+
"gh-dist": "dist/main.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"bd": "bun run build",
|
|
23
|
+
"build": "bun build src/main.ts --install --outdir=dist --format=esm --target=node --external dreamcli",
|
|
24
|
+
"test": "bun test",
|
|
25
|
+
"typecheck": "tsc --noEmit"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"dreamcli": "link:dreamcli"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/bun": "catalog:",
|
|
32
|
+
"typescript": "catalog:"
|
|
33
|
+
},
|
|
34
|
+
"packageManager": "bun@1.3.11",
|
|
35
|
+
"engines": {
|
|
36
|
+
"bun": ">=1.3.11"
|
|
37
|
+
},
|
|
38
|
+
"devEngines": {
|
|
39
|
+
"packageManager": {
|
|
40
|
+
"name": "bun",
|
|
41
|
+
"version": ">=1.3.11"
|
|
42
|
+
},
|
|
43
|
+
"runtime": {
|
|
44
|
+
"name": "bun",
|
|
45
|
+
"version": ">=1.3.11"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authentication commands for the walkthrough `gh` example.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { command, group } from 'dreamcli';
|
|
8
|
+
|
|
9
|
+
import { redactToken, requireAuth, tokenFlag } from '$gh/lib/auth.ts';
|
|
10
|
+
|
|
11
|
+
const authLogin = command('login')
|
|
12
|
+
.description('Authenticate with GitHub')
|
|
13
|
+
.flag(
|
|
14
|
+
'token',
|
|
15
|
+
tokenFlag('Authentication token')
|
|
16
|
+
.required()
|
|
17
|
+
.prompt({ kind: 'input', message: 'Paste your GitHub token:' }),
|
|
18
|
+
)
|
|
19
|
+
.action(({ flags, out }) => {
|
|
20
|
+
const { token } = requireAuth(flags.token);
|
|
21
|
+
const login = {
|
|
22
|
+
host: 'github.com',
|
|
23
|
+
token: redactToken(token),
|
|
24
|
+
storedAt: '~/.config/gh/config.json',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
if (out.jsonMode) {
|
|
28
|
+
out.json(login);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// In a real CLI, validate the token via API and write to config.
|
|
33
|
+
out.log(`Logged in with token ${login.token}`);
|
|
34
|
+
out.info(`Token would be saved to ${login.storedAt}`);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const authStatus = command('status')
|
|
38
|
+
.description('Show authentication status')
|
|
39
|
+
.flag('token', tokenFlag())
|
|
40
|
+
.action(({ flags, out }) => {
|
|
41
|
+
const token = flags.token?.trim();
|
|
42
|
+
const status =
|
|
43
|
+
token === undefined || token.length === 0
|
|
44
|
+
? { authenticated: false, host: 'github.com' }
|
|
45
|
+
: { authenticated: true, host: 'github.com', token: redactToken(token) };
|
|
46
|
+
|
|
47
|
+
if (out.jsonMode) {
|
|
48
|
+
out.json(status);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (status.authenticated) {
|
|
53
|
+
out.log(status.host);
|
|
54
|
+
out.log(`Logged in with token ${status.token}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
out.warn('Not logged in. Run `gh auth login`.');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
export { authLogin, authStatus };
|
|
62
|
+
|
|
63
|
+
export const auth = group('auth')
|
|
64
|
+
.description('Manage authentication')
|
|
65
|
+
.command(authLogin)
|
|
66
|
+
.command(authStatus);
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Issue commands for the walkthrough `gh` example.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { arg, CLIError, flag, group } from 'dreamcli';
|
|
8
|
+
|
|
9
|
+
import issues from '$gh/data/issues.yaml' with { type: 'yaml' };
|
|
10
|
+
import { authedCommand } from '$gh/lib/auth.ts';
|
|
11
|
+
import { normalizeLimit } from '$gh/lib/utils.ts';
|
|
12
|
+
|
|
13
|
+
const issueLabelChoices = Array.from(new Set(issues.flatMap((issue) => issue.labels)))
|
|
14
|
+
.sort()
|
|
15
|
+
.map((label) => ({ value: label }));
|
|
16
|
+
|
|
17
|
+
const issueList = authedCommand('list')
|
|
18
|
+
.description('List issues')
|
|
19
|
+
.flag(
|
|
20
|
+
'state',
|
|
21
|
+
flag.enum(['open', 'closed', 'all']).default('open').alias('s').describe('Filter by state'),
|
|
22
|
+
)
|
|
23
|
+
.flag('limit', flag.number().default(10).alias('L').describe('Maximum number of results'))
|
|
24
|
+
.flag('label', flag.string().alias('l').describe('Filter by label'))
|
|
25
|
+
.action(({ flags, out }) => {
|
|
26
|
+
let results = [...issues];
|
|
27
|
+
|
|
28
|
+
if (flags.state !== 'all') {
|
|
29
|
+
results = results.filter((issue) => issue.state === flags.state);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (flags.label !== undefined) {
|
|
33
|
+
const label = flags.label;
|
|
34
|
+
results = results.filter((issue) => issue.labels.includes(label));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
results = results.slice(0, normalizeLimit(flags.limit));
|
|
38
|
+
|
|
39
|
+
out.table(
|
|
40
|
+
results.map((issue) => ({
|
|
41
|
+
'#': issue.number,
|
|
42
|
+
title: issue.title,
|
|
43
|
+
state: issue.state,
|
|
44
|
+
author: issue.author,
|
|
45
|
+
})),
|
|
46
|
+
);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const issueTriage = authedCommand('triage')
|
|
50
|
+
.description('Triage an issue with guided prompts')
|
|
51
|
+
.arg('number', arg.number().describe('Issue number'))
|
|
52
|
+
.flag('decision', flag.enum(['backlog', 'close']).required().describe('How to handle the issue'))
|
|
53
|
+
.flag('label', flag.array(flag.string()).describe('Labels to keep when leaving the issue open'))
|
|
54
|
+
.flag('comment', flag.boolean().describe('Post a follow-up comment'))
|
|
55
|
+
.interactive(({ flags }) => {
|
|
56
|
+
const labels = flags.label ?? [];
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
label:
|
|
60
|
+
flags.decision === 'backlog' && labels.length === 0
|
|
61
|
+
? {
|
|
62
|
+
kind: 'multiselect',
|
|
63
|
+
message: 'Which labels still fit?',
|
|
64
|
+
choices: issueLabelChoices,
|
|
65
|
+
}
|
|
66
|
+
: false,
|
|
67
|
+
comment:
|
|
68
|
+
flags.decision === 'close' && !flags.comment
|
|
69
|
+
? { kind: 'confirm', message: 'Post a follow-up comment?' }
|
|
70
|
+
: false,
|
|
71
|
+
};
|
|
72
|
+
})
|
|
73
|
+
.action(({ args, flags, out }) => {
|
|
74
|
+
const issue = issues.find((candidate) => candidate.number === args.number);
|
|
75
|
+
|
|
76
|
+
if (!issue) {
|
|
77
|
+
throw new CLIError(`Issue #${args.number} not found`, {
|
|
78
|
+
code: 'NOT_FOUND',
|
|
79
|
+
exitCode: 1,
|
|
80
|
+
suggest: 'Try: gh issue list',
|
|
81
|
+
details: { requested: args.number },
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const selectedLabels = flags.label ?? [];
|
|
86
|
+
const labels =
|
|
87
|
+
flags.decision === 'backlog' && selectedLabels.length > 0 ? selectedLabels : issue.labels;
|
|
88
|
+
const triage = {
|
|
89
|
+
number: issue.number,
|
|
90
|
+
title: issue.title,
|
|
91
|
+
decision: flags.decision,
|
|
92
|
+
state: flags.decision === 'close' ? 'closed' : 'open',
|
|
93
|
+
labels,
|
|
94
|
+
commented: flags.decision === 'close' ? (flags.comment ?? false) : false,
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
if (out.jsonMode) {
|
|
98
|
+
out.json(triage);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
out.log(`#${triage.number} ${triage.title}`);
|
|
103
|
+
if (triage.decision === 'close') {
|
|
104
|
+
out.log('Status: closed');
|
|
105
|
+
if (triage.commented) {
|
|
106
|
+
out.info('Would post a follow-up comment');
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
out.log('Status: open (backlog)');
|
|
112
|
+
out.log(`Labels: ${triage.labels.length > 0 ? triage.labels.join(', ') : 'none'}`);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
export { issueList, issueTriage };
|
|
116
|
+
|
|
117
|
+
export const issue = group('issue')
|
|
118
|
+
.description('Manage issues')
|
|
119
|
+
.command(issueList)
|
|
120
|
+
.command(issueTriage);
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pull request commands for the walkthrough `gh` example.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { arg, CLIError, flag, group } from 'dreamcli';
|
|
8
|
+
|
|
9
|
+
import pullRequests from '$gh/data/pull-requests.yaml' with { type: 'yaml' };
|
|
10
|
+
import { authedCommand } from '$gh/lib/auth.ts';
|
|
11
|
+
import { normalizeLimit, sleep } from '$gh/lib/utils.ts';
|
|
12
|
+
|
|
13
|
+
const prList = authedCommand('list')
|
|
14
|
+
.description('List pull requests')
|
|
15
|
+
.flag(
|
|
16
|
+
'state',
|
|
17
|
+
flag
|
|
18
|
+
.enum(['open', 'closed', 'merged', 'all'])
|
|
19
|
+
.default('open')
|
|
20
|
+
.alias('s')
|
|
21
|
+
.describe('Filter by state'),
|
|
22
|
+
)
|
|
23
|
+
.flag('limit', flag.number().default(10).alias('L').describe('Maximum number of results'))
|
|
24
|
+
.flag('label', flag.string().alias('l').describe('Filter by label'))
|
|
25
|
+
.action(({ flags, out }) => {
|
|
26
|
+
let results = [...pullRequests];
|
|
27
|
+
|
|
28
|
+
if (flags.state !== 'all') {
|
|
29
|
+
results = results.filter((pr) => pr.state === flags.state);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (flags.label !== undefined) {
|
|
33
|
+
const label = flags.label;
|
|
34
|
+
results = results.filter((pr) => pr.labels.includes(label));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
results = results.slice(0, normalizeLimit(flags.limit));
|
|
38
|
+
|
|
39
|
+
out.table(
|
|
40
|
+
results.map((pr) => ({
|
|
41
|
+
'#': pr.number,
|
|
42
|
+
title: pr.title,
|
|
43
|
+
state: pr.state,
|
|
44
|
+
author: pr.author,
|
|
45
|
+
})),
|
|
46
|
+
);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const prView = authedCommand('view')
|
|
50
|
+
.description('View a pull request')
|
|
51
|
+
.arg('number', arg.number().describe('PR number'))
|
|
52
|
+
.action(({ args, out }) => {
|
|
53
|
+
const pr = pullRequests.find((candidate) => candidate.number === args.number);
|
|
54
|
+
|
|
55
|
+
if (!pr) {
|
|
56
|
+
throw new CLIError(`Pull request #${args.number} not found`, {
|
|
57
|
+
code: 'NOT_FOUND',
|
|
58
|
+
exitCode: 1,
|
|
59
|
+
suggest: 'Try: gh pr list',
|
|
60
|
+
details: { requested: args.number },
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (out.jsonMode) {
|
|
65
|
+
out.json(pr);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
out.log(`\
|
|
70
|
+
#${pr.number} ${pr.title}
|
|
71
|
+
State: ${pr.state} Author: ${pr.author} Draft: ${String(pr.draft)}
|
|
72
|
+
Labels: ${pr.labels.join(', ')}`);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const prCreate = authedCommand('create')
|
|
76
|
+
.description('Create a pull request')
|
|
77
|
+
.flag(
|
|
78
|
+
'title',
|
|
79
|
+
flag
|
|
80
|
+
.string()
|
|
81
|
+
.required()
|
|
82
|
+
.alias('t')
|
|
83
|
+
.describe('PR title')
|
|
84
|
+
.prompt({ kind: 'input', message: 'Title:' }),
|
|
85
|
+
)
|
|
86
|
+
.flag(
|
|
87
|
+
'body',
|
|
88
|
+
flag
|
|
89
|
+
.string()
|
|
90
|
+
.required()
|
|
91
|
+
.alias('b')
|
|
92
|
+
.describe('PR body')
|
|
93
|
+
.prompt({ kind: 'input', message: 'Body:' }),
|
|
94
|
+
)
|
|
95
|
+
.flag('draft', flag.boolean().alias('d').default(false).describe('Create as draft'))
|
|
96
|
+
.action(async ({ flags, out }) => {
|
|
97
|
+
const spinner = out.spinner('Creating pull request...');
|
|
98
|
+
await sleep(1500);
|
|
99
|
+
spinner.succeed('Pull request created');
|
|
100
|
+
|
|
101
|
+
const createdPr = {
|
|
102
|
+
number: 143,
|
|
103
|
+
title: flags.title,
|
|
104
|
+
url: 'https://github.com/you/repo/pull/143',
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
if (out.jsonMode) {
|
|
108
|
+
out.json(createdPr);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
out.log(`#${createdPr.number} ${createdPr.title}`);
|
|
113
|
+
if (flags.draft) {
|
|
114
|
+
out.info('Marked as draft');
|
|
115
|
+
}
|
|
116
|
+
out.log(createdPr.url);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
export { prCreate, prList, prView };
|
|
120
|
+
|
|
121
|
+
export const pr = group('pr')
|
|
122
|
+
.description('Manage pull requests')
|
|
123
|
+
.command(prList)
|
|
124
|
+
.command(prView)
|
|
125
|
+
.command(prCreate);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
---
|
|
2
|
+
- { number: 86, title: Dark mode colors wrong, state: open, author: alice, labels: [bug, ui] }
|
|
3
|
+
- { number: 87, title: Typo in README, state: closed, author: grace, labels: [docs] }
|
|
4
|
+
- { number: 88, title: Add keyboard shortcuts, state: open, author: frank, labels: [enhancement] }
|
|
5
|
+
- { number: 89, title: Login fails on Firefox, state: open, author: eve, labels: [bug] }
|