@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

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 (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -1 +1,555 @@
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};
1
+ import { describeNumberConstraintViolation, validateNumberConstraints } from "../schema/number-constraints.mjs";
2
+ import { getFlagAliasNames } from "../schema/flag.mjs";
3
+ import { ParseError } from "../errors/index.mjs";
4
+ //#region src/core/parse/index.ts
5
+ /**
6
+ * Argv tokenization and parsing against command schemas.
7
+ *
8
+ * Two-phase design:
9
+ *
10
+ * 1. **Tokenize** — split raw argv into structured tokens (long flags, short
11
+ * flags, positionals, separator). Schema-agnostic.
12
+ *
13
+ * 2. **Parse** — walk tokens against a {@linkcode CommandSchema} to produce typed raw
14
+ * values. Emits {@linkcode ParseError} for unknown flags, type mismatches, missing
15
+ * values.
16
+ *
17
+ * @module dreamcli/core/parse
18
+ */
19
+ /**
20
+ * Tokenize raw argv into structured tokens.
21
+ *
22
+ * Low-level utility: most apps should use {@link parse}, `cli().run()`, or
23
+ * `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
24
+ * building custom tooling such as debuggers, inspectors, or parser tests.
25
+ *
26
+ * Rules:
27
+ * - `--` → separator (everything after is positional)
28
+ * - `--flag` → long flag, no inline value
29
+ * - `--flag=v` → long flag with inline value
30
+ * - `-abc` → short flags (expanded individually by parser)
31
+ * - `-` → positional (convention: stdin placeholder)
32
+ * - everything else → positional
33
+ *
34
+ * @param argv - Raw argument strings to tokenize
35
+ * @returns Ordered token array ready for {@link parse}
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * tokenize(['deploy', '--force', '--region=eu', '-v']);
40
+ * ```
41
+ */
42
+ function tokenize(argv) {
43
+ const tokens = [];
44
+ let pastSeparator = false;
45
+ for (const raw of argv) {
46
+ if (pastSeparator) {
47
+ tokens.push({
48
+ kind: "positional",
49
+ value: raw
50
+ });
51
+ continue;
52
+ }
53
+ if (raw === "--") {
54
+ tokens.push({ kind: "separator" });
55
+ pastSeparator = true;
56
+ continue;
57
+ }
58
+ if (raw.startsWith("--")) {
59
+ const eqIdx = raw.indexOf("=");
60
+ if (eqIdx !== -1) tokens.push({
61
+ kind: "long-flag",
62
+ name: raw.slice(2, eqIdx),
63
+ value: raw.slice(eqIdx + 1)
64
+ });
65
+ else tokens.push({
66
+ kind: "long-flag",
67
+ name: raw.slice(2),
68
+ value: void 0
69
+ });
70
+ continue;
71
+ }
72
+ if (raw.startsWith("-") && raw.length > 1) {
73
+ tokens.push({
74
+ kind: "short-flags",
75
+ chars: raw.slice(1)
76
+ });
77
+ continue;
78
+ }
79
+ tokens.push({
80
+ kind: "positional",
81
+ value: raw
82
+ });
83
+ }
84
+ return tokens;
85
+ }
86
+ /**
87
+ * Whether `token` appears in argv before the `--` end-of-options separator.
88
+ *
89
+ * Everything at or after the first `--` is a literal positional, so root-level
90
+ * flag interception (`--help` / `--version` / `--json`) must use this instead of
91
+ * a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
92
+ * is wrongly treated as the flag.
93
+ *
94
+ * @param argv - Raw argument strings.
95
+ * @param token - Exact flag token to look for (e.g. `--version`).
96
+ * @returns `true` if `token` occurs before any `--` separator.
97
+ */
98
+ function includesBeforeSeparator(argv, token) {
99
+ for (const arg of argv) {
100
+ if (arg === "--") return false;
101
+ if (arg === token) return true;
102
+ }
103
+ return false;
104
+ }
105
+ /**
106
+ * Remove every occurrence of `token` that appears before the `--` end-of-options
107
+ * separator, leaving post-separator literals untouched.
108
+ *
109
+ * The strip counterpart to {@linkcode includesBeforeSeparator}: root-level flags
110
+ * (`--json`) are stripped before dispatch/parse so the command schema never sees
111
+ * them, but a literal after `--` (`-- --json`) must reach the command unchanged.
112
+ *
113
+ * @param argv - Raw argument strings.
114
+ * @param token - Exact flag token to strip (e.g. `--json`).
115
+ * @returns A new argv with pre-separator occurrences of `token` removed, or the
116
+ * original reference when `token` does not occur before the separator.
117
+ */
118
+ function stripBeforeSeparator(argv, token) {
119
+ const separatorIndex = argv.indexOf("--");
120
+ const head = separatorIndex === -1 ? argv : argv.slice(0, separatorIndex);
121
+ if (!head.includes(token)) return argv;
122
+ const filteredHead = head.filter((arg) => arg !== token);
123
+ return separatorIndex === -1 ? filteredHead : [...filteredHead, ...argv.slice(separatorIndex)];
124
+ }
125
+ /**
126
+ * Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
127
+ *
128
+ * Supports both long names and single-char aliases for short flag expansion.
129
+ *
130
+ * @param flags - Flag schemas keyed by canonical name
131
+ * @returns Lookup map covering all names and aliases
132
+ */
133
+ function buildFlagLookup(flags) {
134
+ const lookup = /* @__PURE__ */ new Map();
135
+ for (const [name, schema] of Object.entries(flags)) {
136
+ lookup.set(name, [name, schema]);
137
+ for (const alias of getFlagAliasNames(schema, { includeHidden: true })) lookup.set(alias, [name, schema]);
138
+ }
139
+ return lookup;
140
+ }
141
+ /**
142
+ * Whether a flag kind expects a value argument (vs. being a bare boolean).
143
+ *
144
+ * @param schema - Flag schema to check
145
+ * @returns `true` if the flag expects a value token after it
146
+ */
147
+ function flagExpectsValue(schema) {
148
+ return schema.kind !== "boolean";
149
+ }
150
+ /**
151
+ * Coerce a raw string to the flag's declared kind.
152
+ *
153
+ * @param flagName - Canonical flag name (for error messages)
154
+ * @param raw - Raw string value from argv
155
+ * @param schema - {@link FlagSchema} declaring the expected kind
156
+ * @returns Coerced value matching the schema's kind
157
+ * @throws ParseError on type mismatch
158
+ */
159
+ function coerceFlagValue(flagName, raw, schema, displayName = `--${flagName}`) {
160
+ switch (schema.kind) {
161
+ case "string": return raw;
162
+ case "number": {
163
+ const n = Number(raw);
164
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
165
+ code: "INVALID_VALUE",
166
+ details: {
167
+ flag: flagName,
168
+ input: displayName,
169
+ value: raw,
170
+ expected: "number"
171
+ }
172
+ });
173
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
174
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}: ${describeNumberConstraintViolation(violation)}`, {
175
+ code: "INVALID_VALUE",
176
+ details: {
177
+ flag: flagName,
178
+ input: displayName,
179
+ value: raw,
180
+ expected: "number",
181
+ constraint: violation.kind,
182
+ ..."bound" in violation ? { bound: violation.bound } : {}
183
+ }
184
+ });
185
+ return n;
186
+ }
187
+ case "boolean":
188
+ if (raw === "true" || raw === "1") return true;
189
+ if (raw === "false" || raw === "0") return false;
190
+ throw new ParseError(`Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`, {
191
+ code: "INVALID_VALUE",
192
+ details: {
193
+ flag: flagName,
194
+ input: displayName,
195
+ value: raw,
196
+ expected: "boolean"
197
+ }
198
+ });
199
+ case "enum": {
200
+ const allowed = schema.enumValues;
201
+ if (allowed === void 0) throw new ParseError(`Enum flag --${flagName} is misconfigured: no allowed values declared`, {
202
+ code: "INVALID_SCHEMA",
203
+ details: {
204
+ flag: flagName,
205
+ kind: "enum",
206
+ missing: "enumValues"
207
+ }
208
+ });
209
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(", ")}`, {
210
+ code: "INVALID_VALUE",
211
+ details: {
212
+ flag: flagName,
213
+ input: displayName,
214
+ value: raw,
215
+ allowed
216
+ }
217
+ });
218
+ return raw;
219
+ }
220
+ case "array":
221
+ if (schema.elementSchema) return coerceFlagValue(flagName, raw, schema.elementSchema);
222
+ return raw;
223
+ case "custom":
224
+ if (!schema.parseFn) return raw;
225
+ try {
226
+ return schema.parseFn(raw);
227
+ } catch (err) {
228
+ if (err instanceof ParseError) throw err;
229
+ throw new ParseError(`Failed to parse flag ${displayName}: ${err instanceof Error ? err.message : String(err)}`, {
230
+ code: "INVALID_VALUE",
231
+ details: {
232
+ flag: flagName,
233
+ input: displayName,
234
+ value: raw
235
+ },
236
+ cause: err
237
+ });
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Coerce a raw string to the arg's declared kind.
243
+ *
244
+ * @param argName - Positional arg name (for error messages)
245
+ * @param raw - Raw string value from argv
246
+ * @param schema - {@link ArgSchema} declaring the expected kind
247
+ * @returns Coerced value matching the schema's kind
248
+ * @throws ParseError on type mismatch or custom parse failure
249
+ */
250
+ function coerceArgValue(argName, raw, schema) {
251
+ switch (schema.kind) {
252
+ case "string": return raw;
253
+ case "number": {
254
+ const n = Number(raw);
255
+ if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
256
+ code: "INVALID_VALUE",
257
+ details: {
258
+ arg: argName,
259
+ value: raw,
260
+ expected: "number"
261
+ }
262
+ });
263
+ const violation = validateNumberConstraints(n, schema.numberConstraints);
264
+ if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>: ${describeNumberConstraintViolation(violation)}`, {
265
+ code: "INVALID_VALUE",
266
+ details: {
267
+ arg: argName,
268
+ value: raw,
269
+ expected: "number",
270
+ constraint: violation.kind,
271
+ ..."bound" in violation ? { bound: violation.bound } : {}
272
+ }
273
+ });
274
+ return n;
275
+ }
276
+ case "enum": {
277
+ const allowed = schema.enumValues;
278
+ if (allowed === void 0) throw new ParseError(`Enum argument <${argName}> is misconfigured: no allowed values declared`, {
279
+ code: "INVALID_SCHEMA",
280
+ details: {
281
+ arg: argName,
282
+ kind: "enum",
283
+ missing: "enumValues"
284
+ }
285
+ });
286
+ if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(", ")}`, {
287
+ code: "INVALID_VALUE",
288
+ details: {
289
+ arg: argName,
290
+ value: raw,
291
+ allowed
292
+ }
293
+ });
294
+ return raw;
295
+ }
296
+ case "custom":
297
+ if (!schema.parseFn) return raw;
298
+ try {
299
+ return schema.parseFn(raw);
300
+ } catch (err) {
301
+ if (err instanceof ParseError) throw err;
302
+ throw new ParseError(`Failed to parse argument <${argName}>: ${err instanceof Error ? err.message : String(err)}`, {
303
+ code: "INVALID_VALUE",
304
+ details: {
305
+ arg: argName,
306
+ value: raw
307
+ },
308
+ cause: err
309
+ });
310
+ }
311
+ }
312
+ }
313
+ /**
314
+ * Parse tokenized argv against a command schema.
315
+ *
316
+ * Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
317
+ * automatically. Call `parse()` directly when you need raw parsed values before
318
+ * env/config/default resolution or when writing custom tooling around schemas.
319
+ *
320
+ * @param schema - The command schema to parse against
321
+ * @param argv - Raw argv strings (NOT including the command name itself)
322
+ * @returns Parsed flag and arg values
323
+ * @throws ParseError for unknown flags, missing values, type mismatches
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * const parsed = parse(deploy.schema, ['production', '--force']);
328
+ * // => { args: { target: 'production' }, flags: { force: true } }
329
+ * ```
330
+ */
331
+ function parse(schema, argv) {
332
+ const tokens = tokenize(argv);
333
+ const flagLookup = buildFlagLookup(schema.flags);
334
+ const flags = {};
335
+ const positionals = [];
336
+ let i = 0;
337
+ while (i < tokens.length) {
338
+ const token = tokens[i];
339
+ if (token === void 0) break;
340
+ if (token.kind === "separator") {
341
+ i++;
342
+ continue;
343
+ }
344
+ if (token.kind === "positional") {
345
+ positionals.push(token.value);
346
+ i++;
347
+ continue;
348
+ }
349
+ if (token.kind === "long-flag") {
350
+ i = parseLongFlag(token, tokens, i, flagLookup, flags);
351
+ continue;
352
+ }
353
+ i = parseShortFlags(token, tokens, i, flagLookup, flags);
354
+ }
355
+ return {
356
+ flags,
357
+ args: mapPositionals(schema.args, positionals)
358
+ };
359
+ }
360
+ /**
361
+ * Parse a long flag token, consuming a value from the next token if needed.
362
+ *
363
+ * @param token - Long-flag token to process
364
+ * @param tokens - Full token array (for lookahead)
365
+ * @param startIdx - Current index of `token` in the array
366
+ * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
367
+ * @param flags - Mutable accumulator for resolved flag values
368
+ * @returns Next index to continue parsing from
369
+ */
370
+ function parseLongFlag(token, tokens, startIdx, flagLookup, flags) {
371
+ const entry = flagLookup.get(token.name);
372
+ if (!entry) {
373
+ const suggestion = suggestFlag(token.name, flagLookup);
374
+ throw new ParseError(`Unknown flag --${token.name}${suggestion ? `. Did you mean --${suggestion}?` : ""}`, {
375
+ code: "UNKNOWN_FLAG",
376
+ details: {
377
+ flag: token.name,
378
+ ...suggestion ? { suggestion } : {}
379
+ },
380
+ ...suggestion ? { suggest: `--${suggestion}` } : {}
381
+ });
382
+ }
383
+ const [canonicalName, flagSchema] = entry;
384
+ if (!flagExpectsValue(flagSchema)) {
385
+ if (token.value !== void 0) flags[canonicalName] = coerceFlagValue(canonicalName, token.value, flagSchema, `--${token.name}`);
386
+ else flags[canonicalName] = true;
387
+ return startIdx + 1;
388
+ }
389
+ if (token.value !== void 0) {
390
+ setFlagValue(flags, canonicalName, flagSchema, token.value);
391
+ return startIdx + 1;
392
+ }
393
+ const nextToken = tokens[startIdx + 1];
394
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag --${token.name} requires a value`, {
395
+ code: "MISSING_VALUE",
396
+ details: {
397
+ flag: canonicalName,
398
+ input: token.name,
399
+ kind: flagSchema.kind
400
+ }
401
+ });
402
+ setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `--${token.name}`);
403
+ return startIdx + 2;
404
+ }
405
+ /**
406
+ * Parse combined short flags, expanding -abc into individual flags.
407
+ *
408
+ * @param token - Short-flags token to expand
409
+ * @param tokens - Full token array (for lookahead)
410
+ * @param startIdx - Current index of `token` in the array
411
+ * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
412
+ * @param flags - Mutable accumulator for resolved flag values
413
+ * @returns Next index to continue parsing from
414
+ */
415
+ function parseShortFlags(token, tokens, startIdx, flagLookup, flags) {
416
+ const { chars } = token;
417
+ let nextIdx = startIdx + 1;
418
+ for (let ci = 0; ci < chars.length; ci++) {
419
+ const ch = chars.charAt(ci);
420
+ const entry = flagLookup.get(ch);
421
+ if (!entry) throw new ParseError(`Unknown flag -${ch}`, {
422
+ code: "UNKNOWN_FLAG",
423
+ details: { flag: ch }
424
+ });
425
+ const [canonicalName, flagSchema] = entry;
426
+ if (!flagExpectsValue(flagSchema)) {
427
+ flags[canonicalName] = true;
428
+ continue;
429
+ }
430
+ if (ci < chars.length - 1) {
431
+ setFlagValue(flags, canonicalName, flagSchema, chars.slice(ci + 1), `-${ch}`);
432
+ break;
433
+ }
434
+ const nextToken = tokens[nextIdx];
435
+ if (nextToken?.kind !== "positional") throw new ParseError(`Flag -${ch} requires a value`, {
436
+ code: "MISSING_VALUE",
437
+ details: {
438
+ flag: canonicalName,
439
+ input: ch,
440
+ kind: flagSchema.kind
441
+ }
442
+ });
443
+ setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `-${ch}`);
444
+ nextIdx++;
445
+ }
446
+ return nextIdx;
447
+ }
448
+ /**
449
+ * Set or accumulate a flag value, handling array flags specially.
450
+ *
451
+ * @param flags - Mutable accumulator for resolved flag values
452
+ * @param name - Canonical flag name
453
+ * @param schema - {@link FlagSchema} declaring the expected kind
454
+ * @param rawValue - Raw string value from argv
455
+ */
456
+ function setFlagValue(flags, name, schema, rawValue, displayName = `--${name}`) {
457
+ const coerced = coerceFlagValue(name, rawValue, schema, displayName);
458
+ if (schema.kind === "array") {
459
+ const existing = flags[name];
460
+ if (Array.isArray(existing)) existing.push(coerced);
461
+ else flags[name] = [coerced];
462
+ } else flags[name] = coerced;
463
+ }
464
+ /**
465
+ * Map positional values to named args based on schema ordering.
466
+ *
467
+ * @param argEntries - Ordered arg schemas from the command
468
+ * @param positionals - Positional values collected during tokenization
469
+ * @returns Named arg values keyed by arg name
470
+ * @throws ParseError if too many positionals and no variadic arg absorbs them
471
+ */
472
+ function mapPositionals(argEntries, positionals) {
473
+ const args = {};
474
+ let posIdx = 0;
475
+ for (const entry of argEntries) {
476
+ if (entry.schema.variadic) {
477
+ const remaining = positionals.slice(posIdx);
478
+ args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
479
+ posIdx = positionals.length;
480
+ break;
481
+ }
482
+ const rawPositional = positionals[posIdx];
483
+ if (rawPositional !== void 0) {
484
+ args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
485
+ posIdx++;
486
+ }
487
+ }
488
+ if (posIdx < positionals.length) {
489
+ const excess = positionals.slice(posIdx);
490
+ throw new ParseError(`Unexpected positional argument${excess.length > 1 ? "s" : ""}: ${excess.join(", ")}`, {
491
+ code: "UNEXPECTED_POSITIONAL",
492
+ details: {
493
+ excess,
494
+ expected: argEntries.length
495
+ }
496
+ });
497
+ }
498
+ return args;
499
+ }
500
+ /**
501
+ * Suggest the closest flag name if the edit distance is small enough.
502
+ *
503
+ * @param input - Misspelled flag name from the user
504
+ * @param lookup - Flag lookup map from {@link buildFlagLookup}
505
+ * @returns Closest flag name, or `undefined` if no close match exists
506
+ */
507
+ function suggestFlag(input, lookup) {
508
+ let bestName;
509
+ let bestDist = Number.POSITIVE_INFINITY;
510
+ const threshold = Math.max(2, Math.floor(input.length / 2));
511
+ for (const key of lookup.keys()) {
512
+ const entry = lookup.get(key);
513
+ if (entry === void 0) continue;
514
+ const [canonicalName, schema] = entry;
515
+ const alias = schema.aliases.find((candidate) => candidate.name === key);
516
+ if (key.length < 2) continue;
517
+ if (key !== canonicalName && alias?.hidden) continue;
518
+ const dist = levenshtein(input, key);
519
+ if (dist < bestDist && dist <= threshold) {
520
+ bestDist = dist;
521
+ bestName = key;
522
+ }
523
+ }
524
+ return bestName;
525
+ }
526
+ /**
527
+ * Classic Levenshtein distance using a single-row DP approach.
528
+ *
529
+ * @param a - First string
530
+ * @param b - Second string
531
+ * @returns Edit distance between `a` and `b`
532
+ */
533
+ function levenshtein(a, b) {
534
+ if (a === b) return 0;
535
+ if (a.length === 0) return b.length;
536
+ if (b.length === 0) return a.length;
537
+ const short = a.length <= b.length ? a : b;
538
+ const long = a.length <= b.length ? b : a;
539
+ const aLen = short.length;
540
+ const bLen = long.length;
541
+ const row = Array.from({ length: aLen + 1 }, (_, i) => i);
542
+ for (let j = 1; j <= bLen; j++) {
543
+ let prev = row[0] ?? 0;
544
+ row[0] = j;
545
+ for (let k = 1; k <= aLen; k++) {
546
+ const cost = short.charAt(k - 1) === long.charAt(j - 1) ? 0 : 1;
547
+ const current = Math.min((row[k] ?? 0) + 1, (row[k - 1] ?? 0) + 1, prev + cost);
548
+ prev = row[k] ?? 0;
549
+ row[k] = current;
550
+ }
551
+ }
552
+ return row[aLen] ?? 0;
553
+ }
554
+ //#endregion
555
+ export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, stripBeforeSeparator, tokenize };
@@ -1,6 +1,5 @@
1
1
  import { ConfirmPromptConfig, InputPromptConfig, PromptConfig, PromptResult, SelectChoice } from "../schema/prompt.mjs";
2
2
  import { WriteFn } from "../output/writer.mjs";
3
-
4
3
  //#region src/core/prompt/index.d.ts
5
4
  /**
6
5
  * A select prompt config with choices guaranteed non-empty.
@@ -105,9 +104,11 @@ declare const PROMPT_CANCEL: unique symbol;
105
104
  * A queued answer consumed by {@link createTestPrompter}.
106
105
  *
107
106
  * The test prompter returns these values exactly as provided; it does not
108
- * coerce or validate them. The normal resolution pipeline performs any later
109
- * type coercion, so tests can supply values in the same shapes real prompts
110
- * would yield:
107
+ * coerce them. The one exception mirrors the terminal prompter: a string answer
108
+ * to an `input` prompt is run through the prompt's `validate` function, and a
109
+ * failing answer is rejected as a cancellation (see {@link createTestPrompter}).
110
+ * The normal resolution pipeline performs any later type coercion, so tests can
111
+ * supply values in the same shapes real prompts would yield:
111
112
  *
112
113
  * - `string` for `input` and `select`
113
114
  * - `boolean` for `confirm`
@@ -139,6 +140,12 @@ interface TestPrompterOptions {
139
140
  * Pass `PROMPT_CANCEL` as an answer to simulate the user cancelling
140
141
  * that prompt.
141
142
  *
143
+ * For `input` prompts that declare a `validate` function, a string answer is
144
+ * validated just as the terminal prompter does. An answer that fails validation
145
+ * is rejected as a cancellation (`{ answered: false }`) — mirroring the terminal
146
+ * prompter exhausting its retries — so prompt validation is integration-testable
147
+ * via {@linkcode runCommand} rather than silently accepted as the resolved value.
148
+ *
142
149
  * @param answers - Ordered queue of answers. Use `PROMPT_CANCEL` for
143
150
  * cancellation.
144
151
  * @param options - Controls behavior when the queue is exhausted.