@kjanat/dreamcli 2.3.0 → 2.4.1

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 (38) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/README.md +94 -34
  3. package/dist/core/cli/index.mjs +1 -1
  4. package/dist/core/cli/planner.mjs +1 -1
  5. package/dist/core/config/package-json.mjs +1 -1
  6. package/dist/core/execution/index.mjs +1 -1
  7. package/dist/core/json-schema/meta-descriptions.generated.d.mts +59 -59
  8. package/dist/core/output/activity.mjs +1 -1
  9. package/dist/core/output/bind.d.mts +37 -0
  10. package/dist/core/output/bind.mjs +1 -0
  11. package/dist/core/output/index.d.mts +6 -1
  12. package/dist/core/output/index.mjs +2 -2
  13. package/dist/core/parse/index.mjs +1 -1
  14. package/dist/core/schema/activity.d.mts +1 -1
  15. package/dist/core/schema/command.d.mts +8 -0
  16. package/dist/core/schema/run.d.mts +8 -5
  17. package/dist/core/schema-dsl/runtime.mjs +1 -1
  18. package/dist/core/testkit/index.mjs +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/runtime/paths.mjs +1 -1
  21. package/dist/strings.d.mts +27 -0
  22. package/dist/strings.mjs +1 -0
  23. package/dist/testkit.mjs +1 -1
  24. package/dist/version.mjs +1 -1
  25. package/package.json +46 -35
  26. package/src/core/cli/index.ts +9 -3
  27. package/src/core/cli/planner.ts +58 -2
  28. package/src/core/config/package-json.ts +3 -2
  29. package/src/core/execution/index.ts +7 -1
  30. package/src/core/help/index.ts +2 -2
  31. package/src/core/output/activity.ts +7 -0
  32. package/src/core/output/bind.ts +59 -0
  33. package/src/core/output/index.ts +35 -0
  34. package/src/core/parse/index.ts +2 -2
  35. package/src/core/schema/command.ts +8 -0
  36. package/src/core/schema/run.ts +8 -5
  37. package/src/runtime/paths.ts +4 -2
  38. package/src/strings.ts +34 -0
@@ -1 +1 @@
1
- import{writeLine as e}from"./writer.mjs";const t={update(){},succeed(){},fail(){},stop(){},wrap(e){return e}},n={increment(){},update(){},done(){},fail(){}};var r=class{stopped=!1;constructor(t,n){this.write=n,e(n,t)}update(e){}succeed(t){this.stopped||(this.stopped=!0,t!==void 0&&e(this.write,t))}fail(t){this.stopped||(this.stopped=!0,t!==void 0&&e(this.write,t))}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}}},i=class{stopped=!1;constructor(t,n){this.write=n,t!==void 0&&e(n,t)}increment(e){}update(e){}done(t){this.stopped||(this.stopped=!0,t!==void 0&&e(this.write,t))}fail(t){this.stopped||(this.stopped=!0,t!==void 0&&e(this.write,t))}};const a=`\x1B[?25l`,o=`\x1B[?25h`,s=`\x1B[2K`,c=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];var l=class{stopped=!1;timer;frameIndex=0;text;constructor(e,t){this.write=t,this.text=e,t(a),this.render(),this.timer=setInterval(()=>{this.frameIndex=(this.frameIndex+1)%c.length,this.render()},80)}render(){let e=c[this.frameIndex]??c[0];this.write(`\r${s}${e} ${this.text}`)}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${s}${o}`)}update(e){this.stopped||(this.text=e,this.render())}succeed(t){this.stopped||(this.stopped=!0,this.cleanup(),t!==void 0&&e(this.write,`✓ ${t}`))}fail(t){this.stopped||(this.stopped=!0,this.cleanup(),t!==void 0&&e(this.write,`✗ ${t}`))}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}}},u=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(a),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${s}${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${s}${o}`)}increment(e){this.stopped||(this.current+=e??1,this.render())}update(e){this.stopped||(this.current=e,this.render())}done(t){this.stopped||(this.stopped=!0,this.cleanup(),t!==void 0&&e(this.write,`✓ ${t}`))}fail(t){this.stopped||(this.stopped=!0,this.cleanup(),t!==void 0&&e(this.write,`✗ ${t}`))}},d=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}}},f=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}))}};export{f as CaptureProgressHandle,d as CaptureSpinnerHandle,i as StaticProgressHandle,r as StaticSpinnerHandle,u as TTYProgressHandle,l as TTYSpinnerHandle,n as noopProgressHandle,t as noopSpinnerHandle};
1
+ import{bindMethods as e}from"./bind.mjs";import{writeLine as t}from"./writer.mjs";const n={update(){},succeed(){},fail(){},stop(){},wrap(e){return e}},r={increment(){},update(){},done(){},fail(){}};var i=class{write;stopped=!1;constructor(n,r){this.write=r,t(r,n),e(this)}update(e){}succeed(e){this.stopped||(this.stopped=!0,e!==void 0&&t(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&t(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}}},a=class{write;stopped=!1;constructor(n,r){this.write=r,n!==void 0&&t(r,n),e(this)}increment(e){}update(e){}done(e){this.stopped||(this.stopped=!0,e!==void 0&&t(this.write,e))}fail(e){this.stopped||(this.stopped=!0,e!==void 0&&t(this.write,e))}};const o=`\x1B[?25l`,s=`\x1B[?25h`,c=`\x1B[2K`,l=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];var u=class{write;stopped=!1;timer;frameIndex=0;text;constructor(t,n){this.write=n,this.text=t,n(o),this.render(),this.timer=setInterval(()=>{this.frameIndex=(this.frameIndex+1)%l.length,this.render()},80),e(this)}render(){let e=l[this.frameIndex]??l[0];this.write(`\r${c}${e} ${this.text}`)}cleanup(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),this.write(`\r${c}${s}`)}update(e){this.stopped||(this.text=e,this.render())}succeed(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&t(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&t(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}}},d=class{write;stopped=!1;timer;current=0;total;label;pulsePos=0;pulseDir=1;constructor(t,n){this.write=n,this.total=t.total,this.label=t.label??``,n(o),this.render(),this.total===void 0&&(this.timer=setInterval(()=>{this.advancePulse(),this.render()},80)),e(this)}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${c}${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${c}${s}`)}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&&t(this.write,`✓ ${e}`))}fail(e){this.stopped||(this.stopped=!0,this.cleanup(),e!==void 0&&t(this.write,`✗ ${e}`))}},f=class{events;stopped=!1;constructor(t,n){this.events=n,n.push({type:`spinner:start`,text:t}),e(this)}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}}},p=class{events;stopped=!1;constructor(t,n){this.events=n,n.push({type:`progress:start`,label:t.label??``,total:t.total}),e(this)}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}))}};export{p as CaptureProgressHandle,f as CaptureSpinnerHandle,a as StaticProgressHandle,i as StaticSpinnerHandle,d as TTYProgressHandle,u as TTYSpinnerHandle,r as noopProgressHandle,n as noopSpinnerHandle};
@@ -0,0 +1,37 @@
1
+ //#region src/core/output/bind.d.ts
2
+ /**
3
+ * Method-binding helper for value objects handed to consumers.
4
+ *
5
+ * Output value objects — the `Out` channel and the spinner/progress handles
6
+ * — expose methods that read instance state via `this`. Consumers naturally
7
+ * detach those methods, either by destructuring
8
+ * (`const { log } = out` / `const { succeed, fail } = spinner`) or by passing
9
+ * them as callbacks (`promise.finally(spinner.stop)`). Detached, an unbound
10
+ * prototype method loses its `this` and crashes on the first field access.
11
+ *
12
+ * {@linkcode bindMethods} eliminates that footgun by installing instance-bound
13
+ * copies of every method, so the ergonomic usage is also the correct one.
14
+ *
15
+ * @module dreamcli/core/output/bind
16
+ * @internal
17
+ */
18
+ /**
19
+ * Bind every method on an instance's prototype chain to the instance.
20
+ *
21
+ * Walks the prototype chain up to (but excluding) `Object.prototype`, binding
22
+ * each method name exactly once — the most-derived definition wins, so subclass
23
+ * overrides (e.g. `CaptureOutputChannel.spinner`) are preserved rather than
24
+ * clobbered by a base-class version. Bound methods are installed as
25
+ * non-enumerable own properties, mirroring the enumerability of the prototype
26
+ * methods they shadow. Getters and non-function members are left untouched.
27
+ *
28
+ * Call this once, last, in a class constructor. Because it reads the live
29
+ * prototype rather than a hand-maintained name list, methods added later are
30
+ * bound automatically — the binding can't silently fall out of date.
31
+ *
32
+ * @param instance - The object whose methods should be bound to it.
33
+ * @internal
34
+ */
35
+ declare function bindMethods(instance: object): void;
36
+ //#endregion
37
+ export { bindMethods };
@@ -0,0 +1 @@
1
+ function e(e){let t=e,n=new Set,r=Object.getPrototypeOf(e);for(;r!==null&&r!==Object.prototype;){for(let i of Object.getOwnPropertyNames(r)){if(i===`constructor`||n.has(i))continue;n.add(i);let a=Object.getOwnPropertyDescriptor(r,i);a===void 0||typeof a.value!=`function`||Object.defineProperty(t,i,{value:a.value.bind(e),writable:!0,enumerable:!1,configurable:!0})}r=Object.getPrototypeOf(r)}}export{e as bindMethods};
@@ -54,6 +54,9 @@ interface ResolvedOutputOptions {
54
54
  readonly verbosity: Verbosity;
55
55
  readonly jsonMode: boolean;
56
56
  }
57
+ declare function setRequestedExitCode(out: Out, code: number): void;
58
+ declare function getRequestedExitCode(out: Out): number | undefined;
59
+ declare function clearRequestedExitCode(out: Out): void;
57
60
  /**
58
61
  * Concrete implementation of the {@linkcode Out} interface.
59
62
  *
@@ -100,6 +103,8 @@ declare class OutputChannel implements Out {
100
103
  warn(message: string): void;
101
104
  /** Error to stderr. Always emitted. */
102
105
  error(message: string): void;
106
+ /** Request a successful-process exit code without writing error output. */
107
+ setExitCode(code: number): void;
103
108
  /**
104
109
  * Emit a structured JSON value to stdout.
105
110
  *
@@ -277,4 +282,4 @@ interface CapturedOutput {
277
282
  */
278
283
  declare function createCaptureOutput(options?: Omit<OutputOptions, 'stdout' | 'stderr'>): [out: Out, captured: CapturedOutput];
279
284
  //#endregion
280
- export { CaptureOutputChannel, CaptureProgressHandle, CaptureSpinnerHandle, type CapturedOutput, OutputChannel, type OutputOptions, StaticProgressHandle, StaticSpinnerHandle, TTYProgressHandle, TTYSpinnerHandle, type Verbosity, type WriteFn, createCaptureOutput, createOutput, noopProgressHandle, noopSpinnerHandle, writeLine };
285
+ export { CaptureOutputChannel, CaptureProgressHandle, CaptureSpinnerHandle, type CapturedOutput, OutputChannel, type OutputOptions, StaticProgressHandle, StaticSpinnerHandle, TTYProgressHandle, TTYSpinnerHandle, type Verbosity, type WriteFn, clearRequestedExitCode, createCaptureOutput, createOutput, getRequestedExitCode, noopProgressHandle, noopSpinnerHandle, setRequestedExitCode, writeLine };
@@ -1,2 +1,2 @@
1
- import{formatDisplayValue as e}from"./display-value.mjs";import{writeLine as t}from"./writer.mjs";import{CaptureProgressHandle as n,CaptureSpinnerHandle as r}from"./activity.mjs";import{resolveOutputPolicy as i,resolveProgressPolicy as a,resolveSpinnerPolicy as o,resolveTableFormat as s,resolveTableTextStream as c,resolveTextStream as l,shouldEmitInfo as u}from"./contracts.mjs";import{createProgressHandleFromPolicy as d,createSpinnerHandleFromPolicy as f,resolveWriterForStream as p}from"./renderers.mjs";const m=()=>{};function h(e){return{stdout:e?.stdout??m,stderr:e?.stderr??m,isTTY:e?.isTTY??!1,verbosity:e?.verbosity??`normal`,jsonMode:e?.jsonMode??!1}}var g=class{options;policy;jsonMode;isTTY;constructor(e){this.options=e,this.policy=i(e),this.jsonMode=e.jsonMode,this.isTTY=e.isTTY}log(e){t(p(this.options,l(this.policy)),e)}info(e){u(this.policy)&&t(p(this.options,l(this.policy)),e)}warn(e){t(this.options.stderr,e)}error(e){t(this.options.stderr,e)}json(e){t(this.options.stdout,JSON.stringify(e))}table(e,n,r){let{columns:i,options:a}=b(n,r),o=s(this.policy,a),c=i??v(e);if(o===`json`){this.json(x(e,c));return}let l=w(e,c);l.length!==0&&t(S(this.options,this.policy,o,a),l)}activeCleanup;stopActive(){this.activeCleanup!==void 0&&(this.activeCleanup(),this.activeCleanup=void 0)}spinner(e,t){let n=f(o(this.policy,t?.fallback??`silent`),e,this.options.stderr);return n.cleanup===void 0?n.handle:(this.stopActive(),this.activeCleanup=n.cleanup,n.handle)}progress(e){let t=d(a(this.policy,e.fallback??`silent`),e,this.options.stderr);return t.cleanup===void 0?t.handle:(this.stopActive(),this.activeCleanup=t.cleanup,t.handle)}},_=class extends g{constructor(e,t){super(e),this.activity=t}spinner(e,t){return new r(e,this.activity)}progress(e){return new n(e,this.activity)}};function v(e){let t=e[0];return t===void 0?[]:Object.keys(t).map(e=>({key:e}))}function y(e){return Array.isArray(e)}function b(e,t){return t===void 0?y(e)?{columns:e,options:t}:{columns:void 0,options:e}:{columns:y(e)?e:void 0,options:t}}function x(e,t){return e.map(e=>Object.fromEntries(t.map(t=>[t.key,e[t.key]])))}function S(e,t,n,r){return n===`json`?e.stdout:p(e,c(t,r))}function C(t){return e(t)}function w(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=>C(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(`
2
- `)}function T(e){return new g(h(e))}function E(e){let t={stdout:[],stderr:[],activity:[]};return[new _(h({...e,stdout:e=>t.stdout.push(e),stderr:e=>t.stderr.push(e)}),t.activity),t]}export{E as createCaptureOutput,T as createOutput};
1
+ import{formatDisplayValue as e}from"./display-value.mjs";import{bindMethods as t}from"./bind.mjs";import{writeLine as n}from"./writer.mjs";import{CaptureProgressHandle as r,CaptureSpinnerHandle as i}from"./activity.mjs";import{resolveOutputPolicy as a,resolveProgressPolicy as o,resolveSpinnerPolicy as s,resolveTableFormat as c,resolveTableTextStream as l,resolveTextStream as u,shouldEmitInfo as d}from"./contracts.mjs";import{createProgressHandleFromPolicy as f,createSpinnerHandleFromPolicy as p,resolveWriterForStream as m}from"./renderers.mjs";const h=()=>{},g=new WeakMap;function _(e){if(!Number.isInteger(e)||e<0||e>255)throw RangeError(`Exit code must be an integer from 0 to 255`);return e}function v(e,t){g.set(e,_(t))}function y(e){return g.get(e)}function b(e){g.delete(e)}function x(e){return{stdout:e?.stdout??h,stderr:e?.stderr??h,isTTY:e?.isTTY??!1,verbosity:e?.verbosity??`normal`,jsonMode:e?.jsonMode??!1}}var S=class{options;policy;jsonMode;isTTY;constructor(e){this.options=e,this.policy=a(e),this.jsonMode=e.jsonMode,this.isTTY=e.isTTY,t(this)}log(e){n(m(this.options,u(this.policy)),e)}info(e){d(this.policy)&&n(m(this.options,u(this.policy)),e)}warn(e){n(this.options.stderr,e)}error(e){n(this.options.stderr,e)}setExitCode(e){v(this,e)}json(e){n(this.options.stdout,JSON.stringify(e))}table(e,t,r){let{columns:i,options:a}=E(t,r),o=c(this.policy,a),s=i??w(e);if(o===`json`){this.json(D(e,s));return}let l=A(e,s);l.length!==0&&n(O(this.options,this.policy,o,a),l)}activeCleanup;stopActive(){this.activeCleanup!==void 0&&(this.activeCleanup(),this.activeCleanup=void 0)}spinner(e,t){let n=p(s(this.policy,t?.fallback??`silent`),e,this.options.stderr);return n.cleanup===void 0?n.handle:(this.stopActive(),this.activeCleanup=n.cleanup,n.handle)}progress(e){let t=f(o(this.policy,e.fallback??`silent`),e,this.options.stderr);return t.cleanup===void 0?t.handle:(this.stopActive(),this.activeCleanup=t.cleanup,t.handle)}},C=class extends S{activity;constructor(e,t){super(e),this.activity=t}spinner(e,t){return new i(e,this.activity)}progress(e){return new r(e,this.activity)}};function w(e){let t=e[0];return t===void 0?[]:Object.keys(t).map(e=>({key:e}))}function T(e){return Array.isArray(e)}function E(e,t){return t===void 0?T(e)?{columns:e,options:t}:{columns:void 0,options:e}:{columns:T(e)?e:void 0,options:t}}function D(e,t){return e.map(e=>Object.fromEntries(t.map(t=>[t.key,e[t.key]])))}function O(e,t,n,r){return n===`json`?e.stdout:m(e,l(t,r))}function k(t){return e(t)}function A(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=>k(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(`
2
+ `)}function j(e){return new S(x(e))}function M(e){let t={stdout:[],stderr:[],activity:[]};return[new C(x({...e,stdout:e=>t.stdout.push(e),stderr:e=>t.stderr.push(e)}),t.activity),t]}export{b as clearRequestedExitCode,M as createCaptureOutput,j as createOutput,y as getRequestedExitCode};
@@ -1 +1 @@
1
- import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(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 r(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}function i(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function a(e){return e.kind!==`boolean`}function o(e,n,r,i=`--${e}`){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 ${i}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,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 ${i}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`boolean`}});case`enum`:{let a=r.enumValues;if(a===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(!a.includes(n))throw new t(`Invalid value '${n}' for flag ${i}. Allowed: ${a.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,allowed:a}});return n}case`array`:return r.elementSchema?o(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 ${i}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n},cause:r})}}}function s(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 c(e,t){let r=n(t),a=i(e.flags),o={},s=[],c=0;for(;c<r.length;){let e=r[c];if(e===void 0)break;if(e.kind===`separator`){c++;continue}if(e.kind===`positional`){s.push(e.value),c++;continue}if(e.kind===`long-flag`){c=l(e,r,c,a,o);continue}c=u(e,r,c,a,o)}return{flags:o,args:f(e.args,s)}}function l(e,n,r,i,s){let c=i.get(e.name);if(!c){let n=p(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[l,u]=c;if(!a(u))return e.value===void 0?s[l]=!0:s[l]=o(l,e.value,u,`--${e.name}`),r+1;if(e.value!==void 0)return d(s,l,u,e.value),r+1;let f=n[r+1];if(!f||f.kind!==`positional`)throw new t(`Flag --${e.name} requires a value`,{code:`MISSING_VALUE`,details:{flag:l,input:e.name,kind:u.kind}});return d(s,l,u,f.value,`--${e.name}`),r+2}function u(e,n,r,i,o){let{chars:s}=e,c=r+1;for(let e=0;e<s.length;e++){let r=s.charAt(e),l=i.get(r);if(!l)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[u,f]=l;if(!a(f)){o[u]=!0;continue}if(e<s.length-1){d(o,u,f,s.slice(e+1),`-${r}`);break}let p=n[c];if(!p||p.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:u,input:r,kind:f.kind}});d(o,u,f,p.value,`-${r}`),c++}return c}function d(e,t,n,r,i=`--${t}`){let a=o(t,r,n,i);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(a):e[t]=[a]}else e[t]=a}function f(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=>s(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=s(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 p(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){let o=t.get(a);if(o===void 0)continue;let[s,c]=o,l=c.aliases.find(e=>e.name===a);if(a.length<2||a!==s&&l?.hidden)continue;let u=m(e,a);u<r&&u<=i&&(r=u,n=a)}return n}function m(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}export{i as buildFlagLookup,a as flagExpectsValue,r as includesBeforeSeparator,c as parse,n as tokenize};
1
+ import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(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 r(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}function i(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function a(e){return e.kind!==`boolean`}function o(e,n,r,i=`--${e}`){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 ${i}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,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 ${i}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`boolean`}});case`enum`:{let a=r.enumValues;if(a===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(!a.includes(n))throw new t(`Invalid value '${n}' for flag ${i}. Allowed: ${a.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,allowed:a}});return n}case`array`:return r.elementSchema?o(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 ${i}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n},cause:r})}}}function s(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 c(e,t){let r=n(t),a=i(e.flags),o={},s=[],c=0;for(;c<r.length;){let e=r[c];if(e===void 0)break;if(e.kind===`separator`){c++;continue}if(e.kind===`positional`){s.push(e.value),c++;continue}if(e.kind===`long-flag`){c=l(e,r,c,a,o);continue}c=u(e,r,c,a,o)}return{flags:o,args:f(e.args,s)}}function l(e,n,r,i,s){let c=i.get(e.name);if(!c){let n=p(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[l,u]=c;if(!a(u))return e.value===void 0?s[l]=!0:s[l]=o(l,e.value,u,`--${e.name}`),r+1;if(e.value!==void 0)return d(s,l,u,e.value),r+1;let f=n[r+1];if(f?.kind!==`positional`)throw new t(`Flag --${e.name} requires a value`,{code:`MISSING_VALUE`,details:{flag:l,input:e.name,kind:u.kind}});return d(s,l,u,f.value,`--${e.name}`),r+2}function u(e,n,r,i,o){let{chars:s}=e,c=r+1;for(let e=0;e<s.length;e++){let r=s.charAt(e),l=i.get(r);if(!l)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[u,f]=l;if(!a(f)){o[u]=!0;continue}if(e<s.length-1){d(o,u,f,s.slice(e+1),`-${r}`);break}let p=n[c];if(p?.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:u,input:r,kind:f.kind}});d(o,u,f,p.value,`-${r}`),c++}return c}function d(e,t,n,r,i=`--${t}`){let a=o(t,r,n,i);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(a):e[t]=[a]}else e[t]=a}function f(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=>s(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=s(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 p(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){let o=t.get(a);if(o===void 0)continue;let[s,c]=o,l=c.aliases.find(e=>e.name===a);if(a.length<2||a!==s&&l?.hidden)continue;let u=m(e,a);u<r&&u<=i&&(r=u,n=a)}return n}function m(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}export{i as buildFlagLookup,a as flagExpectsValue,r as includesBeforeSeparator,c as parse,n as tokenize};
@@ -166,4 +166,4 @@ interface TableOptionsText {
166
166
  /** Per-call rendering options for {@link Out.table}. */
167
167
  type TableOptions = TableOptionsAuto | TableOptionsJson | TableOptionsText;
168
168
  //#endregion
169
- export { type ActivityEvent, type Fallback, type ProgressHandle, type ProgressOptions, type SpinnerHandle, type SpinnerOptions, type TableColumn, type TableFormat, type TableOptions, type TableOptionsAuto, type TableOptionsJson, type TableOptionsText, type TableStream };
169
+ export type { ActivityEvent, Fallback, ProgressHandle, ProgressOptions, SpinnerHandle, SpinnerOptions, TableColumn, TableFormat, TableOptions, TableOptionsAuto, TableOptionsJson, TableOptionsText, TableStream };
@@ -116,6 +116,14 @@ interface Out {
116
116
  warn(message: string): void;
117
117
  /** Error to stderr. */
118
118
  error(message: string): void;
119
+ /**
120
+ * Request a process exit code without emitting error-shaped output.
121
+ *
122
+ * Use this for check/status commands that should print normal output but
123
+ * still signal a non-zero status to scripts. This does not stop execution;
124
+ * later calls overwrite earlier calls, and thrown errors still win.
125
+ */
126
+ setExitCode(code: number): void;
119
127
  /**
120
128
  * Emit a structured JSON value to stdout.
121
129
  *
@@ -133,9 +133,10 @@ interface RunOptions {
133
133
  /**
134
134
  * Structured result from {@linkcode runCommand}.
135
135
  *
136
- * Contains the exit code, captured stdout/stderr output, recorded
137
- * {@linkcode ActivityEvent | activity events}, and an `error` field
138
- * that is `undefined` on success and a {@linkcode CLIError} on failure.
136
+ * Contains the exit code, captured stdout/stderr output, recorded
137
+ * {@linkcode ActivityEvent | activity events}, and an `error` field.
138
+ * `error` is `undefined` when execution completed without throwing, even if
139
+ * the handler requested a non-zero status via {@linkcode Out.setExitCode}.
139
140
  *
140
141
  * @example
141
142
  * ```ts
@@ -162,8 +163,10 @@ interface RunResult {
162
163
  */
163
164
  readonly activity: readonly ActivityEvent[];
164
165
  /**
165
- * The error that caused a non-zero exit, or `undefined` on success.
166
- * {@linkcode CLIError} instances are preserved; unknown errors are wrapped.
166
+ * The error that caused a failure, or `undefined` when execution completed.
167
+ * A non-zero `exitCode` can still have no error when a handler calls
168
+ * {@linkcode Out.setExitCode}. {@linkcode CLIError} instances are preserved;
169
+ * unknown errors are wrapped.
167
170
  */
168
171
  readonly error: CLIError | undefined;
169
172
  }
@@ -1,2 +1,2 @@
1
1
  const e={"{":`lbrace`,"}":`rbrace`,"[":`lbracket`,"]":`rbracket`,"<":`langle`,">":`rangle`,",":`comma`,":":`colon`,";":`semicolon`,"?":`question`,"|":`pipe`};function t(e){return e===` `||e===`
2
- `||e===` `||e===`\r`}function n(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`_`||e===`$`}function r(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`||e===`$`}function i(i){let a=[],o=0;for(;o<i.length;){let s=i[o]??``;if(t(s)){o++;continue}let c=e[s];if(c!==void 0){a.push({kind:c,value:s}),o++;continue}if(s===`'`){let e=``;for(o++;o<i.length&&i[o]!==`'`;)e+=i[o],o++;if(o>=i.length)throw SyntaxError(`Unterminated string literal`);o++,a.push({kind:`string_literal`,value:e});continue}if(s===`@`){o++;let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}if(e.length===0)throw SyntaxError(`Expected identifier after '@' at position ${String(o)}`);a.push({kind:`ref`,value:e});continue}if(r(s)){let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}a.push({kind:`ident`,value:e});continue}throw SyntaxError(`Unexpected character '${s}' at position ${String(o)}`)}return a}const a=new Set([`string`,`number`,`integer`,`boolean`,`true`,`false`,`null`,`undefined`,`unknown`,`never`]);function o(e){switch(e){case`string`:return{kind:`string`};case`number`:return{kind:`number`};case`integer`:return{kind:`integer`};case`boolean`:return{kind:`boolean`};case`true`:return{kind:`true`};case`false`:return{kind:`false`};case`null`:return{kind:`null`};case`undefined`:return{kind:`undefined`};case`unknown`:return{kind:`unknown`};case`never`:return{kind:`never`};default:throw SyntaxError(`Unknown type '${e}'`)}}var s=class{pos=0;constructor(e){this.tokens=e}parseRoot(){let e=this.parseValue();if(this.pos<this.tokens.length){let e=this.peek();throw SyntaxError(`Unexpected token '${e?.value??`?`}' at position ${String(this.pos)}`)}return e}parseValue(){return this.parseUnion()}parseUnion(){let e=this.parsePostfix();if(!this.check(`pipe`))return e;let t=[e];for(;this.match(`pipe`);)t.push(this.parsePostfix());return{kind:`union`,members:t}}parsePostfix(){let e=this.parsePrimary();for(;this.check(`lbracket`)&&this.checkAt(this.pos+1,`rbracket`);)this.advance(),this.advance(),e={kind:`array`,element:e};return e}parsePrimary(){if(this.check(`lbrace`))return this.parseObject();if(this.check(`string_literal`))return{kind:`literal`,value:this.advance().value};if(this.check(`ref`))return{kind:`ref`,target:this.advance().value};let e=this.expectIdent();if(e===`Record`){if(this.expect(`langle`),this.parseValue().kind!==`string`)throw SyntaxError(`Record key type must be 'string' because JSON object keys are always strings`);this.expect(`comma`);let e=this.parseValue();return this.expect(`rangle`),{kind:`record`,value:e}}if(!a.has(e))throw SyntaxError(`Unknown type '${e}' at position ${String(this.pos-1)}`);return o(e)}parseObject(){this.expect(`lbrace`);let e={};for(;!this.check(`rbrace`);){let t=this.expectIdent();if(Object.hasOwn(e,t))throw SyntaxError(`Duplicate property '${t}' at position ${String(this.pos-1)}`);let n=this.match(`question`);this.expect(`colon`),e[t]={optional:n,schema:this.parseValue()},this.match(`semicolon`)}return this.expect(`rbrace`),{kind:`object`,properties:e}}peek(){return this.tokens[this.pos]}check(e){return this.peek()?.kind===e}checkAt(e,t){return this.tokens[e]?.kind===t}advance(){let e=this.tokens[this.pos];if(e===void 0)throw SyntaxError(`Unexpected end of input`);return this.pos++,e}match(e){return this.check(e)?(this.pos++,!0):!1}expect(e){if(!this.check(e)){let t=this.peek();throw SyntaxError(t?`Expected '${e}' but got '${t.kind}' ('${t.value}') at position ${String(this.pos)}`:`Expected '${e}' but reached end of input`)}return this.advance()}expectIdent(){return this.expect(`ident`).value}};function c(e){return new s(i(e)).parseRoot()}export{c as parseSchema};
2
+ `||e===` `||e===`\r`}function n(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`_`||e===`$`}function r(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`||e===`$`}function i(i){let a=[],o=0;for(;o<i.length;){let s=i[o]??``;if(t(s)){o++;continue}let c=e[s];if(c!==void 0){a.push({kind:c,value:s}),o++;continue}if(s===`'`){let e=``;for(o++;o<i.length&&i[o]!==`'`;)e+=i[o],o++;if(o>=i.length)throw SyntaxError(`Unterminated string literal`);o++,a.push({kind:`string_literal`,value:e});continue}if(s===`@`){o++;let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}if(e.length===0)throw SyntaxError(`Expected identifier after '@' at position ${String(o)}`);a.push({kind:`ref`,value:e});continue}if(r(s)){let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}a.push({kind:`ident`,value:e});continue}throw SyntaxError(`Unexpected character '${s}' at position ${String(o)}`)}return a}const a=new Set([`string`,`number`,`integer`,`boolean`,`true`,`false`,`null`,`undefined`,`unknown`,`never`]);function o(e){switch(e){case`string`:return{kind:`string`};case`number`:return{kind:`number`};case`integer`:return{kind:`integer`};case`boolean`:return{kind:`boolean`};case`true`:return{kind:`true`};case`false`:return{kind:`false`};case`null`:return{kind:`null`};case`undefined`:return{kind:`undefined`};case`unknown`:return{kind:`unknown`};case`never`:return{kind:`never`};default:throw SyntaxError(`Unknown type '${e}'`)}}var s=class{tokens;pos=0;constructor(e){this.tokens=e}parseRoot(){let e=this.parseValue();if(this.pos<this.tokens.length){let e=this.peek();throw SyntaxError(`Unexpected token '${e?.value??`?`}' at position ${String(this.pos)}`)}return e}parseValue(){return this.parseUnion()}parseUnion(){let e=this.parsePostfix();if(!this.check(`pipe`))return e;let t=[e];for(;this.match(`pipe`);)t.push(this.parsePostfix());return{kind:`union`,members:t}}parsePostfix(){let e=this.parsePrimary();for(;this.check(`lbracket`)&&this.checkAt(this.pos+1,`rbracket`);)this.advance(),this.advance(),e={kind:`array`,element:e};return e}parsePrimary(){if(this.check(`lbrace`))return this.parseObject();if(this.check(`string_literal`))return{kind:`literal`,value:this.advance().value};if(this.check(`ref`))return{kind:`ref`,target:this.advance().value};let e=this.expectIdent();if(e===`Record`){if(this.expect(`langle`),this.parseValue().kind!==`string`)throw SyntaxError(`Record key type must be 'string' because JSON object keys are always strings`);this.expect(`comma`);let e=this.parseValue();return this.expect(`rangle`),{kind:`record`,value:e}}if(!a.has(e))throw SyntaxError(`Unknown type '${e}' at position ${String(this.pos-1)}`);return o(e)}parseObject(){this.expect(`lbrace`);let e={};for(;!this.check(`rbrace`);){let t=this.expectIdent();if(Object.hasOwn(e,t))throw SyntaxError(`Duplicate property '${t}' at position ${String(this.pos-1)}`);let n=this.match(`question`);this.expect(`colon`),e[t]={optional:n,schema:this.parseValue()},this.match(`semicolon`)}return this.expect(`rbrace`),{kind:`object`,properties:e}}peek(){return this.tokens[this.pos]}check(e){return this.peek()?.kind===e}checkAt(e,t){return this.tokens[e]?.kind===t}advance(){let e=this.tokens[this.pos];if(e===void 0)throw SyntaxError(`Unexpected end of input`);return this.pos++,e}match(e){return this.check(e)?(this.pos++,!0):!1}expect(e){if(!this.check(e)){let t=this.peek();throw SyntaxError(t?`Expected '${e}' but got '${t.kind}' ('${t.value}') at position ${String(this.pos)}`:`Expected '${e}' but reached end of input`)}return this.advance()}expectIdent(){return this.expect(`ident`).value}};function c(e){return new s(i(e)).parseRoot()}export{c as parseSchema};
@@ -1 +1 @@
1
- import{buildRunResult as e,executeCommand as t}from"../execution/index.mjs";import{createCaptureOutput as n}from"../output/index.mjs";async function r(r,i,a){let o,s;if(a?.out!==void 0)o=a.out,s=a.captured??{stdout:[],stderr:[],activity:[]};else{let e={...a?.verbosity===void 0?{}:{verbosity:a.verbosity},...a?.jsonMode===void 0?{}:{jsonMode:a.jsonMode},...a?.isTTY===void 0?{}:{isTTY:a.isTTY}};[o,s]=n(Object.keys(e).length>0?e:void 0)}let c=a?.mergedSchema??r.schema,l=a?.meta??{name:c.name,bin:a?.help?.binName??c.name,version:void 0,command:c.name};return e(await t({command:r,argv:i,out:o,schema:c,meta:l,...a===void 0?{}:{options:a}}),s)}export{r as runCommand};
1
+ import{createCaptureOutput as e}from"../output/index.mjs";import{buildRunResult as t,executeCommand as n}from"../execution/index.mjs";async function r(r,i,a){let o,s;if(a?.out!==void 0)o=a.out,s=a.captured??{stdout:[],stderr:[],activity:[]};else{let t={...a?.verbosity===void 0?{}:{verbosity:a.verbosity},...a?.jsonMode===void 0?{}:{jsonMode:a.jsonMode},...a?.isTTY===void 0?{}:{isTTY:a.isTTY}};[o,s]=e(Object.keys(t).length>0?t:void 0)}let c=a?.mergedSchema??r.schema,l=a?.meta??{name:c.name,bin:a?.help?.binName??c.name,version:void 0,command:c.name};return t(await n({command:r,argv:i,out:o,schema:c,meta:l,...a===void 0?{}:{options:a}}),s)}export{r as runCommand};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
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{osc8 as h,visibleWidth as g}from"./core/help/ansi.mjs";import{formatHelp as _}from"./core/help/index.mjs";import{parse as v,tokenize as y}from"./core/parse/index.mjs";import{createTerminalPrompter as b,resolvePromptConfig as x}from"./core/prompt/index.mjs";import{resolve as S}from"./core/resolve/index.mjs";import{createOutput as C}from"./core/output/index.mjs";import{ArgBuilder as w,arg as T,createArgSchema as E}from"./core/schema/arg.mjs";import{CommandBuilder as D,command as O,group as k}from"./core/schema/command.mjs";import{discoverPackageJson as A,inferCliName as j,packageRepositoryUrl as M}from"./core/config/package-json.mjs";import{plugin as N}from"./core/cli/plugin.mjs";import{buildConfigSearchPaths as P,configFormat as F,discoverConfig as I}from"./core/config/index.mjs";import{CLIBuilder as L,cli as R}from"./core/cli/index.mjs";import{definitionMetaSchema as z,generateInputSchema as B,generateSchema as V}from"./core/json-schema/index.mjs";import{middleware as H}from"./core/schema/middleware.mjs";export{w as ArgBuilder,L as CLIBuilder,o as CLIError,D as CommandBuilder,e as FlagBuilder,s as ParseError,p as SHELLS,c as ValidationError,T as arg,P as buildConfigSearchPaths,R as cli,O as command,F as configFormat,E as createArgSchema,C as createOutput,t as createSchema,b as createTerminalPrompter,z as definitionMetaSchema,I as discoverConfig,A as discoverPackageJson,n as flag,_ as formatHelp,r as generateBashCompletion,m as generateCompletion,i as generateFishCompletion,B as generateInputSchema,a as generatePowerShellCompletion,V as generateSchema,f as generateZshCompletion,k as group,j as inferCliName,l as isCLIError,u as isParseError,d as isValidationError,H as middleware,h as osc8,M as packageRepositoryUrl,v as parse,N as plugin,S as resolve,x as resolvePromptConfig,y as tokenize,g as visibleWidth};
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{osc8 as h,visibleWidth as g}from"./core/help/ansi.mjs";import{formatHelp as _}from"./core/help/index.mjs";import{createOutput as v}from"./core/output/index.mjs";import{parse as y,tokenize as b}from"./core/parse/index.mjs";import{createTerminalPrompter as x,resolvePromptConfig as S}from"./core/prompt/index.mjs";import{resolve as C}from"./core/resolve/index.mjs";import{ArgBuilder as w,arg as T,createArgSchema as E}from"./core/schema/arg.mjs";import{CommandBuilder as D,command as O,group as k}from"./core/schema/command.mjs";import{discoverPackageJson as A,inferCliName as j,packageRepositoryUrl as M}from"./core/config/package-json.mjs";import{plugin as N}from"./core/cli/plugin.mjs";import{buildConfigSearchPaths as P,configFormat as F,discoverConfig as I}from"./core/config/index.mjs";import{CLIBuilder as L,cli as R}from"./core/cli/index.mjs";import{definitionMetaSchema as z,generateInputSchema as B,generateSchema as V}from"./core/json-schema/index.mjs";import{middleware as H}from"./core/schema/middleware.mjs";export{w as ArgBuilder,L as CLIBuilder,o as CLIError,D as CommandBuilder,e as FlagBuilder,s as ParseError,p as SHELLS,c as ValidationError,T as arg,P as buildConfigSearchPaths,R as cli,O as command,F as configFormat,E as createArgSchema,v as createOutput,t as createSchema,x as createTerminalPrompter,z as definitionMetaSchema,I as discoverConfig,A as discoverPackageJson,n as flag,_ as formatHelp,r as generateBashCompletion,m as generateCompletion,i as generateFishCompletion,B as generateInputSchema,a as generatePowerShellCompletion,V as generateSchema,f as generateZshCompletion,k as group,j as inferCliName,l as isCLIError,u as isParseError,d as isValidationError,H as middleware,h as osc8,M as packageRepositoryUrl,y as parse,N as plugin,C as resolve,S as resolvePromptConfig,b as tokenize,g as visibleWidth};
@@ -1 +1 @@
1
- function e(e,t){return t?e.USERPROFILE?e.USERPROFILE:e.HOMEDRIVE&&e.HOMEPATH?e.HOMEDRIVE+e.HOMEPATH:e.HOME||`C:\\`:e.HOME||`/`}function t(e,t,n){if(t)return e.APPDATA!==void 0&&e.APPDATA!==``?e.APPDATA:`${n.replace(/[\\/]+$/,``)||n}\\AppData\\Roaming`;let r=n.replace(/\/+$/,``);return e.XDG_CONFIG_HOME!==void 0&&e.XDG_CONFIG_HOME!==``?e.XDG_CONFIG_HOME:r.length===0?`/.config`:`${r}/.config`}export{t as resolveConfigDirectory,e as resolveHomeDirectory};
1
+ import{stripTrailing as e}from"../strings.mjs";function t(e,t){return t?e.USERPROFILE?e.USERPROFILE:e.HOMEDRIVE&&e.HOMEPATH?e.HOMEDRIVE+e.HOMEPATH:e.HOME||`C:\\`:e.HOME||`/`}function n(t,n,r){if(n)return t.APPDATA!==void 0&&t.APPDATA!==``?t.APPDATA:`${e(r,[47,92])||r}\\AppData\\Roaming`;let i=e(r,[47]);return t.XDG_CONFIG_HOME!==void 0&&t.XDG_CONFIG_HOME!==``?t.XDG_CONFIG_HOME:i.length===0?`/.config`:`${i}/.config`}export{n as resolveConfigDirectory,t as resolveHomeDirectory};
@@ -0,0 +1,27 @@
1
+ //#region src/strings.d.ts
2
+ /**
3
+ * Internal string utilities shared across runtime and core modules.
4
+ *
5
+ * @module dreamcli/strings
6
+ */
7
+ /** Character code for `/` (forward slash). */
8
+ declare const SLASH = 47;
9
+ /** Character code for `\` (backslash). */
10
+ declare const BACKSLASH = 92;
11
+ /**
12
+ * Remove trailing characters whose code points appear in `codes`.
13
+ *
14
+ * Linear-time replacement for trailing-character regexes such as
15
+ * `/[\\/]+$/`. Those patterns are polynomial-ReDoS prone: the engine
16
+ * greedily consumes the run, fails the end anchor, backtracks one
17
+ * character at a time, and repeats that work from every start position —
18
+ * O(n²) on adversarial input. This scan is O(n) with no backtracking.
19
+ *
20
+ * @param input - Source string.
21
+ * @param codes - Character codes to strip from the end of `input`.
22
+ * @returns `input` with all trailing matching characters removed.
23
+ * @internal
24
+ */
25
+ declare function stripTrailing(input: string, codes: readonly number[]): string;
26
+ //#endregion
27
+ export { BACKSLASH, SLASH, stripTrailing };
@@ -0,0 +1 @@
1
+ function e(e,t){let n=e.length;for(;n>0&&t.includes(e.charCodeAt(n-1));)--n;return n===e.length?e:e.slice(0,n)}export{e as stripTrailing};
package/dist/testkit.mjs CHANGED
@@ -1 +1 @@
1
- import{PROMPT_CANCEL as e,createTestPrompter as t}from"./core/prompt/index.mjs";import{createCaptureOutput as n}from"./core/output/index.mjs";import{runCommand as r}from"./core/testkit/index.mjs";import{createTestAdapter as i}from"./runtime/adapter.mjs";export{e as PROMPT_CANCEL,n as createCaptureOutput,i as createTestAdapter,t as createTestPrompter,r as runCommand};
1
+ import{createCaptureOutput as e}from"./core/output/index.mjs";import{PROMPT_CANCEL as t,createTestPrompter as n}from"./core/prompt/index.mjs";import{runCommand as r}from"./core/testkit/index.mjs";import{createTestAdapter as i}from"./runtime/adapter.mjs";export{t as PROMPT_CANCEL,e as createCaptureOutput,i as createTestAdapter,n as createTestPrompter,r as runCommand};
package/dist/version.mjs CHANGED
@@ -1 +1 @@
1
- const e=`2.3.0`,t=`23cad0f`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
1
+ const e=`2.4.1`,t=`a683cd2`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "2.3.0",
3
+ "version": "2.4.1",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
+ "dreamcli",
6
7
  "cli",
7
8
  "typescript",
8
9
  "framework",
9
10
  "schema-first",
10
11
  "command-line"
11
12
  ],
12
- "homepage": "https://dreamcli.kjanat.com",
13
+ "homepage": "https://dreamcli.kjanat.dev",
13
14
  "bugs": {
14
15
  "url": "https://github.com/kjanat/dreamcli/issues"
15
16
  },
@@ -72,15 +73,17 @@
72
73
  "./examples/*"
73
74
  ],
74
75
  "scripts": {
75
- "bd": "bunx --bun tsdown",
76
- "build": "bunx --bun tsdown",
77
- "build:watch": "bunx --bun tsdown --watch",
78
- "ci": "bun typecheck && bun lint && bun run format:check && bun run meta-descriptions:check && bun run test && bun run docs:build && bun bd",
76
+ "bd": "run build",
77
+ "build": "bun --bun tsdown",
78
+ "build:watch": "run build --watch",
79
+ "ci": "run -pk typecheck lint format:check meta-descriptions:check test docs:build bd",
79
80
  "coverage": "vitest run --coverage",
80
- "dev": "bunx --bun tsdown --logLevel silent --watch & bunx --bun vitepress@next dev docs --host --port ${PORT:-5173} & wait",
81
- "docs:build": "bunx --bun vitepress@next build docs",
82
- "docs:dev": "bunx --bun vitepress@next dev docs",
83
- "docs:preview": "bunx --bun vitepress@next preview docs",
81
+ "dev": "run -p build:watch docs:dev",
82
+ "docs:build": "bun --bun vitepress build docs",
83
+ "docs:deploy": "wrangler deploy",
84
+ "docs:dev": "bun --bun vitepress dev docs --host --port ${PORT:-5173}",
85
+ "docs:preview": "bun --bun vitepress preview docs",
86
+ "docs:upload": "wrangler versions upload",
84
87
  "fmt": "dprint fmt",
85
88
  "fmt:autofix": "dprint fmt --allow-no-files --excludes .github",
86
89
  "fmt:update": "dprint config update --yes --recursive",
@@ -98,40 +101,48 @@
98
101
  "lint:fix": "biome lint --fix",
99
102
  "meta-descriptions": "bun --bun scripts/build-meta-descriptions.ts",
100
103
  "meta-descriptions:check": "bun --bun scripts/build-meta-descriptions.ts --check",
101
- "prepack": "bunx --bun tsdown --logLevel silent",
104
+ "prepack": "bun --bun tsdown --logLevel silent",
105
+ "publish:preview": "bunx pkg-pr-new publish --bun --comment=update --packageManager=bun,npm",
106
+ "schema:emit": "bun scripts/emit-definition-schema.ts",
102
107
  "test": "vitest run",
108
+ "test:bun": "bun --bun vitest run",
109
+ "test:gh": "run --dir examples/gh test",
110
+ "test:node": "npx -y vitest run",
103
111
  "test:watch": "vitest",
104
112
  "typecheck": "tsgo --noEmit",
113
+ "typecheck:gh": "run --dir examples/gh typecheck",
105
114
  "typecheck:tsc": "tsc --noEmit",
106
- "upgrade": "bun update --latest && bun add -D vitepress@next"
115
+ "upgrade": "bun update --latest && bun add -D vitepress@next",
116
+ "version:check": "bun scripts/check-version-sync.ts"
107
117
  },
108
118
  "overrides": {
109
119
  "vitepress": "next"
110
120
  },
111
121
  "devDependencies": {
112
- "@arethetypeswrong/core": "^0.18.2",
113
- "@biomejs/biome": "^2.4.10",
122
+ "@arethetypeswrong/core": "^0.18.4",
123
+ "@biomejs/biome": "^2.5.1",
114
124
  "@iarna/toml": "^2.2.5",
115
- "@shikijs/transformers": "^4.0.2",
116
- "@shikijs/vitepress-twoslash": "^4.0.2",
117
- "@types/bun": "^1.3.12",
118
- "@types/deno": "^2.5.0",
125
+ "@shikijs/transformers": "^4.2.0",
126
+ "@shikijs/vitepress-twoslash": "^4.2.0",
127
+ "@types/bun": "^1.3.14",
128
+ "@types/deno": "^2.7.0",
119
129
  "@types/node": ">=22.0.0, <23.0.0",
120
- "@typescript/native-preview": "^7.0.0-dev.20260406.1",
121
- "@vitest/coverage-v8": "^4.1.2",
122
- "dprint": "^0.53.2",
130
+ "@typescript/native-preview": "^7.0.0-dev",
131
+ "@vitest/coverage-v8": "^4.1.9",
132
+ "dprint": "^0.54.0",
123
133
  "floating-vue": "^5.2.2",
124
- "knip": "^6.3.0",
125
- "mermaid": "^11.14.0",
126
- "publint": "^0.3.18",
127
- "tsdown": "^0.21.7",
128
- "typedoc": "^0.28.18",
129
- "typescript": "^6.0.2",
130
- "vite": "^8",
134
+ "knip": "^6.18.0",
135
+ "mermaid": "^11.15.0",
136
+ "publint": "^0.3.21",
137
+ "runner-run": "0.14.0",
138
+ "tsdown": "^0.22.3",
139
+ "typedoc": "^0.28.19",
140
+ "typescript": "^6.0.3",
141
+ "vite": "^8.1.0",
131
142
  "vitepress": "^2.0.0-alpha.17",
132
- "vitest": "^4.1.2",
133
- "wrangler": "^4.80.0",
134
- "yaml": "^2.8.3"
143
+ "vitest": "^4.1.9",
144
+ "wrangler": "^4.104.0",
145
+ "yaml": "^2.9.0"
135
146
  },
136
147
  "packageManager": "bun@1.3.14",
137
148
  "engines": {
@@ -150,16 +161,16 @@
150
161
  }
151
162
  },
152
163
  "volta": {
153
- "node": "25.9.0",
154
- "npm": "11.12.1"
164
+ "node": "26.3.1",
165
+ "npm": "11.17.0"
155
166
  },
156
167
  "publishConfig": {
157
168
  "access": "public",
158
169
  "provenance": true
159
170
  },
160
171
  "catalog": {
161
- "@types/bun": "^1.3.12",
172
+ "@types/bun": "^1.3.14",
162
173
  "@types/node": ">=22.0.0, <23.0.0",
163
- "typescript": "^6.0.2"
174
+ "typescript": "^6.0.3"
164
175
  }
165
176
  }
@@ -18,7 +18,11 @@ import { buildRunResult, executeCommand } from '#internals/core/execution/index.
18
18
  import type { HelpOptions } from '#internals/core/help/index.ts';
19
19
  import { formatHelp } from '#internals/core/help/index.ts';
20
20
  import type { CapturedOutput } from '#internals/core/output/index.ts';
21
- import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
21
+ import {
22
+ clearRequestedExitCode,
23
+ createCaptureOutput,
24
+ createOutput,
25
+ } from '#internals/core/output/index.ts';
22
26
  import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
23
27
  import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
24
28
  import { arg } from '#internals/core/schema/arg.ts';
@@ -36,6 +40,7 @@ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
36
40
  import { runCommand } from '#internals/core/testkit/index.ts';
37
41
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
38
42
  import { createAdapter } from '#internals/runtime/auto.ts';
43
+ import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts';
39
44
  import type { HelpLinks } from './help-links.ts';
40
45
  import { deriveHelpLinks } from './help-links.ts';
41
46
  import type { OutputPolicy } from './planner.ts';
@@ -826,6 +831,7 @@ class CLIBuilder {
826
831
  Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
827
832
  );
828
833
  }
834
+ clearRequestedExitCode(out);
829
835
 
830
836
  // Resolve help options — default binName to CLI program name,
831
837
  // hyperlinks to TTY detection (escapes never leak into piped output)
@@ -985,7 +991,7 @@ const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
985
991
  * @internal
986
992
  */
987
993
  function basename(input: string): string | undefined {
988
- const trimmed = input.replace(/[\\/]+$/g, '');
994
+ const trimmed = stripTrailing(input, [SLASH, BACKSLASH]);
989
995
  if (trimmed.length === 0) return undefined;
990
996
  const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
991
997
  const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
@@ -1197,6 +1203,7 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1197
1203
 
1198
1204
  // --- Exports
1199
1205
 
1206
+ export type { HelpLinks } from './help-links.ts';
1200
1207
  export type {
1201
1208
  BeforeParseParams,
1202
1209
  CLIPlugin,
@@ -1204,6 +1211,5 @@ export type {
1204
1211
  PluginCommandContext,
1205
1212
  ResolvedCommandParams,
1206
1213
  } from './plugin.ts';
1207
- export type { HelpLinks } from './help-links.ts';
1208
1214
  export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
1209
1215
  export { CLIBuilder, cli, formatRootHelp, plugin };
@@ -12,8 +12,12 @@
12
12
 
13
13
  import { CLIError, ParseError } from '#internals/core/errors/index.ts';
14
14
  import type { HelpOptions } from '#internals/core/help/index.ts';
15
- import { buildFlagLookup, includesBeforeSeparator } from '#internals/core/parse/index.ts';
16
15
  import type { OutputPolicy } from '#internals/core/output/contracts.ts';
16
+ import {
17
+ buildFlagLookup,
18
+ flagExpectsValue,
19
+ includesBeforeSeparator,
20
+ } from '#internals/core/parse/index.ts';
17
21
  import type { CommandMeta, CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
18
22
  import { dispatch, findClosestCommand } from './dispatch.ts';
19
23
  import type { CLIPlugin } from './plugin.ts';
@@ -249,6 +253,44 @@ function buildPlannerMatchOutcome(
249
253
  };
250
254
  }
251
255
 
256
+ function canDelegateUnknownRootToDefault(command: ErasedCommand, input: string): boolean {
257
+ return input === '' || command.schema.args.length > 0;
258
+ }
259
+
260
+ function findUnknownFlagBeforePositional(
261
+ argv: readonly string[],
262
+ flags: CommandSchema['flags'],
263
+ ): string | undefined {
264
+ const lookup = buildFlagLookup(flags);
265
+
266
+ for (let index = 0; index < argv.length; index++) {
267
+ const token = argv[index];
268
+ if (token === undefined || token === '--') return undefined;
269
+ if (token === '-' || !token.startsWith('-')) return undefined;
270
+
271
+ if (token.startsWith('--')) {
272
+ const equalsIndex = token.indexOf('=');
273
+ const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
274
+ const entry = lookup.get(name);
275
+ if (entry === undefined) return equalsIndex === -1 ? token : `--${name}`;
276
+ if (equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
277
+ continue;
278
+ }
279
+
280
+ const chars = token.slice(1);
281
+ for (let charIndex = 0; charIndex < chars.length; charIndex++) {
282
+ const char = chars.charAt(charIndex);
283
+ const entry = lookup.get(char);
284
+ if (entry === undefined) return `-${char}`;
285
+ if (!flagExpectsValue(entry[1])) continue;
286
+ if (charIndex === chars.length - 1) index++;
287
+ break;
288
+ }
289
+ }
290
+
291
+ return undefined;
292
+ }
293
+
252
294
  /**
253
295
  * Decide what to do with an argv invocation before any command executes.
254
296
  *
@@ -342,7 +384,7 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
342
384
  if (defaultCommand !== undefined && result.parentPath.length === 0) {
343
385
  const suggestion =
344
386
  result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
345
- if (suggestion === undefined) {
387
+ if (suggestion === undefined && canDelegateUnknownRootToDefault(defaultCommand, result.input)) {
346
388
  return buildPlannerMatchOutcome(
347
389
  options.schema,
348
390
  defaultCommand,
@@ -352,6 +394,20 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
352
394
  options.output,
353
395
  );
354
396
  }
397
+
398
+ const unknownFlag = findUnknownFlagBeforePositional(
399
+ filteredArgv,
400
+ defaultCommand.schema.flags,
401
+ );
402
+ if (unknownFlag !== undefined) {
403
+ return {
404
+ kind: 'dispatch-error',
405
+ error: new ParseError(`Unknown flag ${unknownFlag}`, {
406
+ code: 'UNKNOWN_FLAG',
407
+ suggest: `Run '${options.schema.name} --help' for available commands`,
408
+ }),
409
+ };
410
+ }
355
411
  }
356
412
 
357
413
  if (result.input === '') {
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
12
+ import { SLASH, stripTrailing } from '#internals/strings.ts';
12
13
 
13
14
  // --- Narrowing helpers
14
15
 
@@ -297,13 +298,13 @@ function packageRepositoryUrl(pkg: PackageJsonData): string | undefined {
297
298
  // scp-style locator: `git@github.com:u/r.git`
298
299
  const scp = /^git@([^:/]+):(.+)$/.exec(locator);
299
300
  if (scp !== null && scp[1] !== undefined && scp[2] !== undefined) {
300
- return `https://${scp[1]}/${stripGitSuffix(scp[2].replace(/\/+$/, ''))}`;
301
+ return `https://${scp[1]}/${stripGitSuffix(stripTrailing(scp[2], [SLASH]))}`;
301
302
  }
302
303
 
303
304
  if (!/^(?:https?|git|ssh):\/\//.test(locator)) return undefined;
304
305
  try {
305
306
  const url = new URL(locator);
306
- const path = stripGitSuffix(url.pathname.replace(/\/+$/, ''));
307
+ const path = stripGitSuffix(stripTrailing(url.pathname, [SLASH]));
307
308
  return `https://${url.hostname}${path}`;
308
309
  } catch {
309
310
  return undefined;
@@ -16,6 +16,10 @@ import type {
16
16
  import { CLIError } from '#internals/core/errors/index.ts';
17
17
  import { formatHelp } from '#internals/core/help/index.ts';
18
18
  import type { CapturedOutput } from '#internals/core/output/index.ts';
19
+ import {
20
+ clearRequestedExitCode,
21
+ getRequestedExitCode,
22
+ } from '#internals/core/output/index.ts';
19
23
  import { includesBeforeSeparator, parse } from '#internals/core/parse/index.ts';
20
24
  import { createTestPrompter } from '#internals/core/prompt/index.ts';
21
25
  import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
@@ -67,6 +71,7 @@ interface CommandExecutionResult {
67
71
  */
68
72
  async function executeCommand(request: CommandExecutionRequest): Promise<CommandExecutionResult> {
69
73
  const { argv, command, meta, options, out, schema } = request;
74
+ clearRequestedExitCode(out);
70
75
 
71
76
  try {
72
77
  if (includesBeforeSeparator(argv, '--help') || includesBeforeSeparator(argv, '-h')) {
@@ -123,7 +128,7 @@ async function executeCommand(request: CommandExecutionRequest): Promise<Command
123
128
  await executeWithExecutionSteps(command, handler, resolved.flags, resolved.args, out, meta);
124
129
  await runResolvedHooks(options?.plugins, 'afterAction', resolvedParams);
125
130
 
126
- return { exitCode: 0, error: undefined };
131
+ return { exitCode: getRequestedExitCode(out) ?? 0, error: undefined };
127
132
  } catch (error: unknown) {
128
133
  if (error instanceof CLIError) {
129
134
  if (options?.jsonMode === true) {
@@ -150,6 +155,7 @@ async function executeCommand(request: CommandExecutionRequest): Promise<Command
150
155
  return { exitCode: 1, error: wrapped };
151
156
  } finally {
152
157
  out.stopActive();
158
+ clearRequestedExitCode(out);
153
159
  }
154
160
  }
155
161