@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,681 +0,0 @@
1
- /**
2
- * Argv tokenization and parsing against command schemas.
3
- *
4
- * Two-phase design:
5
- *
6
- * 1. **Tokenize** — split raw argv into structured tokens (long flags, short
7
- * flags, positionals, separator). Schema-agnostic.
8
- *
9
- * 2. **Parse** — walk tokens against a {@linkcode CommandSchema} to produce typed raw
10
- * values. Emits {@linkcode ParseError} for unknown flags, type mismatches, missing
11
- * values.
12
- *
13
- * @module dreamcli/core/parse
14
- */
15
-
16
- import { ParseError } from '#internals/core/errors/index.ts';
17
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
18
- import type {
19
- ArgSchema,
20
- CommandArgEntry,
21
- CommandSchema,
22
- FlagSchema,
23
- } from '#internals/core/schema/index.ts';
24
-
25
- // --- Tokenizer — schema-agnostic argv splitting
26
-
27
- /**
28
- * Token discriminated union.
29
- *
30
- * The tokenizer produces these from raw argv strings. The parser then
31
- * interprets them against a command schema.
32
- */
33
- type Token =
34
- | { readonly kind: 'long-flag'; readonly name: string; readonly value: string | undefined }
35
- | { readonly kind: 'short-flags'; readonly chars: string }
36
- | { readonly kind: 'positional'; readonly value: string }
37
- | { readonly kind: 'separator' };
38
-
39
- /**
40
- * Tokenize raw argv into structured tokens.
41
- *
42
- * Low-level utility: most apps should use {@link parse}, `cli().run()`, or
43
- * `runCommand()` instead of tokenizing manually. Reach for `tokenize()` when
44
- * building custom tooling such as debuggers, inspectors, or parser tests.
45
- *
46
- * Rules:
47
- * - `--` → separator (everything after is positional)
48
- * - `--flag` → long flag, no inline value
49
- * - `--flag=v` → long flag with inline value
50
- * - `-abc` → short flags (expanded individually by parser)
51
- * - `-` → positional (convention: stdin placeholder)
52
- * - everything else → positional
53
- *
54
- * @param argv - Raw argument strings to tokenize
55
- * @returns Ordered token array ready for {@link parse}
56
- *
57
- * @example
58
- * ```ts
59
- * tokenize(['deploy', '--force', '--region=eu', '-v']);
60
- * ```
61
- */
62
- function tokenize(argv: readonly string[]): readonly Token[] {
63
- const tokens: Token[] = [];
64
- let pastSeparator = false;
65
-
66
- for (const raw of argv) {
67
- if (pastSeparator) {
68
- tokens.push({ kind: 'positional', value: raw });
69
- continue;
70
- }
71
-
72
- if (raw === '--') {
73
- tokens.push({ kind: 'separator' });
74
- pastSeparator = true;
75
- continue;
76
- }
77
-
78
- if (raw.startsWith('--')) {
79
- const eqIdx = raw.indexOf('=');
80
- if (eqIdx !== -1) {
81
- tokens.push({
82
- kind: 'long-flag',
83
- name: raw.slice(2, eqIdx),
84
- value: raw.slice(eqIdx + 1),
85
- });
86
- } else {
87
- tokens.push({ kind: 'long-flag', name: raw.slice(2), value: undefined });
88
- }
89
- continue;
90
- }
91
-
92
- // Single `-` is a positional (stdin convention), not a flag
93
- if (raw.startsWith('-') && raw.length > 1) {
94
- tokens.push({ kind: 'short-flags', chars: raw.slice(1) });
95
- continue;
96
- }
97
-
98
- tokens.push({ kind: 'positional', value: raw });
99
- }
100
-
101
- return tokens;
102
- }
103
-
104
- /**
105
- * Whether `token` appears in argv before the `--` end-of-options separator.
106
- *
107
- * Everything at or after the first `--` is a literal positional, so root-level
108
- * flag interception (`--help` / `--version` / `--json`) must use this instead of
109
- * a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
110
- * is wrongly treated as the flag.
111
- *
112
- * @param argv - Raw argument strings.
113
- * @param token - Exact flag token to look for (e.g. `--version`).
114
- * @returns `true` if `token` occurs before any `--` separator.
115
- */
116
- function includesBeforeSeparator(argv: readonly string[], token: string): boolean {
117
- for (const arg of argv) {
118
- if (arg === '--') return false;
119
- if (arg === token) return true;
120
- }
121
- return false;
122
- }
123
-
124
- // --- Parse result
125
-
126
- /**
127
- * Raw parsed values before resolution (defaults, env, config, etc.).
128
- *
129
- * Flag values are `unknown` because type coercion happens here but the
130
- * generic type info lives in the schema builders, not at runtime.
131
- */
132
- interface ParseResult {
133
- /** Flag values keyed by canonical flag name. */
134
- readonly flags: Readonly<Record<string, unknown>>;
135
- /** Positional arg values keyed by arg name. */
136
- readonly args: Readonly<Record<string, unknown>>;
137
- }
138
-
139
- // --- Internal lookup helpers
140
-
141
- /**
142
- * Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
143
- *
144
- * Supports both long names and single-char aliases for short flag expansion.
145
- *
146
- * @param flags - Flag schemas keyed by canonical name
147
- * @returns Lookup map covering all names and aliases
148
- */
149
- function buildFlagLookup(
150
- flags: Readonly<Record<string, FlagSchema>>,
151
- ): ReadonlyMap<string, readonly [name: string, schema: FlagSchema]> {
152
- const lookup = new Map<string, readonly [string, FlagSchema]>();
153
- for (const [name, schema] of Object.entries(flags)) {
154
- lookup.set(name, [name, schema]);
155
- for (const alias of getFlagAliasNames(schema, { includeHidden: true })) {
156
- lookup.set(alias, [name, schema]);
157
- }
158
- }
159
- return lookup;
160
- }
161
-
162
- /**
163
- * Whether a flag kind expects a value argument (vs. being a bare boolean).
164
- *
165
- * @param schema - Flag schema to check
166
- * @returns `true` if the flag expects a value token after it
167
- */
168
- function flagExpectsValue(schema: FlagSchema): boolean {
169
- return schema.kind !== 'boolean';
170
- }
171
-
172
- // --- Value coercion
173
-
174
- /**
175
- * Coerce a raw string to the flag's declared kind.
176
- *
177
- * @param flagName - Canonical flag name (for error messages)
178
- * @param raw - Raw string value from argv
179
- * @param schema - {@link FlagSchema} declaring the expected kind
180
- * @returns Coerced value matching the schema's kind
181
- * @throws ParseError on type mismatch
182
- */
183
- function coerceFlagValue(
184
- flagName: string,
185
- raw: string,
186
- schema: FlagSchema,
187
- displayName = `--${flagName}`,
188
- ): unknown {
189
- switch (schema.kind) {
190
- case 'string':
191
- return raw;
192
-
193
- case 'number': {
194
- const n = Number(raw);
195
- if (Number.isNaN(n)) {
196
- throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
197
- code: 'INVALID_VALUE',
198
- details: { flag: flagName, input: displayName, value: raw, expected: 'number' },
199
- });
200
- }
201
- return n;
202
- }
203
-
204
- case 'boolean':
205
- // Explicit boolean values: --flag=true / --flag=false
206
- if (raw === 'true' || raw === '1') return true;
207
- if (raw === 'false' || raw === '0') return false;
208
- throw new ParseError(
209
- `Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`,
210
- {
211
- code: 'INVALID_VALUE',
212
- details: { flag: flagName, input: displayName, value: raw, expected: 'boolean' },
213
- },
214
- );
215
-
216
- case 'enum': {
217
- const allowed = schema.enumValues;
218
- if (allowed === undefined) {
219
- throw new ParseError(
220
- `Enum flag --${flagName} is misconfigured: no allowed values declared`,
221
- {
222
- code: 'INVALID_SCHEMA',
223
- details: { flag: flagName, kind: 'enum', missing: 'enumValues' },
224
- },
225
- );
226
- }
227
- if (!allowed.includes(raw)) {
228
- throw new ParseError(
229
- `Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(', ')}`,
230
- {
231
- code: 'INVALID_VALUE',
232
- details: { flag: flagName, input: displayName, value: raw, allowed },
233
- },
234
- );
235
- }
236
- return raw;
237
- }
238
-
239
- case 'array':
240
- // Array element — coerce via element schema if present
241
- if (schema.elementSchema) {
242
- return coerceFlagValue(flagName, raw, schema.elementSchema);
243
- }
244
- return raw;
245
-
246
- case 'custom': {
247
- if (!schema.parseFn) {
248
- return raw;
249
- }
250
- try {
251
- return schema.parseFn(raw);
252
- } catch (err) {
253
- if (err instanceof ParseError) throw err;
254
- const message = err instanceof Error ? err.message : String(err);
255
- throw new ParseError(`Failed to parse flag ${displayName}: ${message}`, {
256
- code: 'INVALID_VALUE',
257
- details: { flag: flagName, input: displayName, value: raw },
258
- cause: err,
259
- });
260
- }
261
- }
262
- }
263
- }
264
-
265
- /**
266
- * Coerce a raw string to the arg's declared kind.
267
- *
268
- * @param argName - Positional arg name (for error messages)
269
- * @param raw - Raw string value from argv
270
- * @param schema - {@link ArgSchema} declaring the expected kind
271
- * @returns Coerced value matching the schema's kind
272
- * @throws ParseError on type mismatch or custom parse failure
273
- */
274
- function coerceArgValue(argName: string, raw: string, schema: ArgSchema): unknown {
275
- switch (schema.kind) {
276
- case 'string':
277
- return raw;
278
-
279
- case 'number': {
280
- const n = Number(raw);
281
- if (Number.isNaN(n)) {
282
- throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
283
- code: 'INVALID_VALUE',
284
- details: { arg: argName, value: raw, expected: 'number' },
285
- });
286
- }
287
- return n;
288
- }
289
-
290
- case 'enum': {
291
- const allowed = schema.enumValues;
292
- if (allowed === undefined) {
293
- throw new ParseError(
294
- `Enum argument <${argName}> is misconfigured: no allowed values declared`,
295
- {
296
- code: 'INVALID_SCHEMA',
297
- details: { arg: argName, kind: 'enum', missing: 'enumValues' },
298
- },
299
- );
300
- }
301
- if (!allowed.includes(raw)) {
302
- throw new ParseError(
303
- `Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(', ')}`,
304
- {
305
- code: 'INVALID_VALUE',
306
- details: { arg: argName, value: raw, allowed },
307
- },
308
- );
309
- }
310
- return raw;
311
- }
312
-
313
- case 'custom': {
314
- if (!schema.parseFn) {
315
- return raw;
316
- }
317
- try {
318
- return schema.parseFn(raw);
319
- } catch (err) {
320
- if (err instanceof ParseError) throw err;
321
- const message = err instanceof Error ? err.message : String(err);
322
- throw new ParseError(`Failed to parse argument <${argName}>: ${message}`, {
323
- code: 'INVALID_VALUE',
324
- details: { arg: argName, value: raw },
325
- cause: err,
326
- });
327
- }
328
- }
329
- }
330
- }
331
-
332
- // --- Parser — schema-aware token interpretation
333
-
334
- /**
335
- * Parse tokenized argv against a command schema.
336
- *
337
- * Low-level API: most apps should let `cli()` or `runCommand()` handle parsing
338
- * automatically. Call `parse()` directly when you need raw parsed values before
339
- * env/config/default resolution or when writing custom tooling around schemas.
340
- *
341
- * @param schema - The command schema to parse against
342
- * @param argv - Raw argv strings (NOT including the command name itself)
343
- * @returns Parsed flag and arg values
344
- * @throws ParseError for unknown flags, missing values, type mismatches
345
- *
346
- * @example
347
- * ```ts
348
- * const parsed = parse(deploy.schema, ['production', '--force']);
349
- * // => { args: { target: 'production' }, flags: { force: true } }
350
- * ```
351
- */
352
- function parse(schema: CommandSchema, argv: readonly string[]): ParseResult {
353
- const tokens = tokenize(argv);
354
- const flagLookup = buildFlagLookup(schema.flags);
355
-
356
- // Mutable accumulators — frozen in the result
357
- const flags: Record<string, unknown> = {};
358
- const positionals: string[] = [];
359
-
360
- let i = 0;
361
- while (i < tokens.length) {
362
- const token = tokens[i];
363
- if (token === undefined) break; // unreachable — loop guard ensures i < length
364
-
365
- if (token.kind === 'separator') {
366
- i++;
367
- continue;
368
- }
369
-
370
- if (token.kind === 'positional') {
371
- positionals.push(token.value);
372
- i++;
373
- continue;
374
- }
375
-
376
- if (token.kind === 'long-flag') {
377
- i = parseLongFlag(token, tokens, i, flagLookup, flags);
378
- continue;
379
- }
380
-
381
- // token.kind === 'short-flags'
382
- i = parseShortFlags(token, tokens, i, flagLookup, flags);
383
- }
384
-
385
- // Map positionals to named args
386
- const args = mapPositionals(schema.args, positionals);
387
-
388
- return { flags, args };
389
- }
390
-
391
- // --- Long flag parsing
392
-
393
- /**
394
- * Parse a long flag token, consuming a value from the next token if needed.
395
- *
396
- * @param token - Long-flag token to process
397
- * @param tokens - Full token array (for lookahead)
398
- * @param startIdx - Current index of `token` in the array
399
- * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
400
- * @param flags - Mutable accumulator for resolved flag values
401
- * @returns Next index to continue parsing from
402
- */
403
- function parseLongFlag(
404
- token: { readonly kind: 'long-flag'; readonly name: string; readonly value: string | undefined },
405
- tokens: readonly Token[],
406
- startIdx: number,
407
- flagLookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
408
- flags: Record<string, unknown>,
409
- ): number {
410
- const entry = flagLookup.get(token.name);
411
- if (!entry) {
412
- const suggestion = suggestFlag(token.name, flagLookup);
413
- throw new ParseError(
414
- `Unknown flag --${token.name}${suggestion ? `. Did you mean --${suggestion}?` : ''}`,
415
- {
416
- code: 'UNKNOWN_FLAG',
417
- details: { flag: token.name, ...(suggestion ? { suggestion } : {}) },
418
- ...(suggestion ? { suggest: `--${suggestion}` } : {}),
419
- },
420
- );
421
- }
422
-
423
- const [canonicalName, flagSchema] = entry;
424
-
425
- if (!flagExpectsValue(flagSchema)) {
426
- // Boolean flag
427
- if (token.value !== undefined) {
428
- flags[canonicalName] = coerceFlagValue(
429
- canonicalName,
430
- token.value,
431
- flagSchema,
432
- `--${token.name}`,
433
- );
434
- } else {
435
- flags[canonicalName] = true;
436
- }
437
- return startIdx + 1;
438
- }
439
-
440
- if (token.value !== undefined) {
441
- // --flag=value (inline)
442
- setFlagValue(flags, canonicalName, flagSchema, token.value);
443
- return startIdx + 1;
444
- }
445
-
446
- // --flag value (next token is the value)
447
- const nextToken = tokens[startIdx + 1];
448
- if (nextToken?.kind !== 'positional') {
449
- throw new ParseError(`Flag --${token.name} requires a value`, {
450
- code: 'MISSING_VALUE',
451
- details: { flag: canonicalName, input: token.name, kind: flagSchema.kind },
452
- });
453
- }
454
- setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `--${token.name}`);
455
- return startIdx + 2;
456
- }
457
-
458
- // --- Short flag parsing
459
-
460
- /**
461
- * Parse combined short flags, expanding -abc into individual flags.
462
- *
463
- * @param token - Short-flags token to expand
464
- * @param tokens - Full token array (for lookahead)
465
- * @param startIdx - Current index of `token` in the array
466
- * @param flagLookup - Name/alias → [canonical, schema] map from {@link buildFlagLookup}
467
- * @param flags - Mutable accumulator for resolved flag values
468
- * @returns Next index to continue parsing from
469
- */
470
- function parseShortFlags(
471
- token: { readonly kind: 'short-flags'; readonly chars: string },
472
- tokens: readonly Token[],
473
- startIdx: number,
474
- flagLookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
475
- flags: Record<string, unknown>,
476
- ): number {
477
- const { chars } = token;
478
- let nextIdx = startIdx + 1;
479
-
480
- for (let ci = 0; ci < chars.length; ci++) {
481
- const ch = chars.charAt(ci);
482
- const entry = flagLookup.get(ch);
483
- if (!entry) {
484
- throw new ParseError(`Unknown flag -${ch}`, {
485
- code: 'UNKNOWN_FLAG',
486
- details: { flag: ch },
487
- });
488
- }
489
-
490
- const [canonicalName, flagSchema] = entry;
491
-
492
- if (!flagExpectsValue(flagSchema)) {
493
- // Boolean short flag
494
- flags[canonicalName] = true;
495
- continue;
496
- }
497
-
498
- if (ci < chars.length - 1) {
499
- // Value-expecting flag in the middle of combined shorts:
500
- // -oFile → -o with value "File" (rest of chars is the value)
501
- const inlineValue = chars.slice(ci + 1);
502
- setFlagValue(flags, canonicalName, flagSchema, inlineValue, `-${ch}`);
503
- break; // consumed all remaining chars
504
- }
505
-
506
- // Last char in the group — consume next token as value
507
- const nextToken = tokens[nextIdx];
508
- if (nextToken?.kind !== 'positional') {
509
- throw new ParseError(`Flag -${ch} requires a value`, {
510
- code: 'MISSING_VALUE',
511
- details: { flag: canonicalName, input: ch, kind: flagSchema.kind },
512
- });
513
- }
514
- setFlagValue(flags, canonicalName, flagSchema, nextToken.value, `-${ch}`);
515
- nextIdx++;
516
- }
517
-
518
- return nextIdx;
519
- }
520
-
521
- // --- Flag value setter (handles array accumulation)
522
-
523
- /**
524
- * Set or accumulate a flag value, handling array flags specially.
525
- *
526
- * @param flags - Mutable accumulator for resolved flag values
527
- * @param name - Canonical flag name
528
- * @param schema - {@link FlagSchema} declaring the expected kind
529
- * @param rawValue - Raw string value from argv
530
- */
531
- function setFlagValue(
532
- flags: Record<string, unknown>,
533
- name: string,
534
- schema: FlagSchema,
535
- rawValue: string,
536
- displayName = `--${name}`,
537
- ): void {
538
- const coerced = coerceFlagValue(name, rawValue, schema, displayName);
539
-
540
- if (schema.kind === 'array') {
541
- const existing = flags[name];
542
- if (Array.isArray(existing)) {
543
- existing.push(coerced);
544
- } else {
545
- flags[name] = [coerced];
546
- }
547
- } else {
548
- flags[name] = coerced;
549
- }
550
- }
551
-
552
- // --- Positional arg mapping
553
-
554
- /**
555
- * Map positional values to named args based on schema ordering.
556
- *
557
- * @param argEntries - Ordered arg schemas from the command
558
- * @param positionals - Positional values collected during tokenization
559
- * @returns Named arg values keyed by arg name
560
- * @throws ParseError if too many positionals and no variadic arg absorbs them
561
- */
562
- function mapPositionals(
563
- argEntries: readonly CommandArgEntry[],
564
- positionals: readonly string[],
565
- ): Record<string, unknown> {
566
- const args: Record<string, unknown> = {};
567
- let posIdx = 0;
568
-
569
- for (const entry of argEntries) {
570
- if (entry.schema.variadic) {
571
- // Variadic arg consumes all remaining positionals
572
- const remaining = positionals.slice(posIdx);
573
- args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
574
- posIdx = positionals.length;
575
- break;
576
- }
577
-
578
- const rawPositional = positionals[posIdx];
579
- if (rawPositional !== undefined) {
580
- args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
581
- posIdx++;
582
- }
583
- // If no positional available, leave absent (resolution/validation handles defaults/required)
584
- }
585
-
586
- // Check for excess positionals
587
- if (posIdx < positionals.length) {
588
- const excess = positionals.slice(posIdx);
589
- throw new ParseError(
590
- `Unexpected positional argument${excess.length > 1 ? 's' : ''}: ${excess.join(', ')}`,
591
- {
592
- code: 'UNEXPECTED_POSITIONAL',
593
- details: { excess, expected: argEntries.length },
594
- },
595
- );
596
- }
597
-
598
- return args;
599
- }
600
-
601
- // --- Suggestion helper (Levenshtein-based "did you mean?")
602
-
603
- /**
604
- * Suggest the closest flag name if the edit distance is small enough.
605
- *
606
- * @param input - Misspelled flag name from the user
607
- * @param lookup - Flag lookup map from {@link buildFlagLookup}
608
- * @returns Closest flag name, or `undefined` if no close match exists
609
- */
610
- function suggestFlag(
611
- input: string,
612
- lookup: ReadonlyMap<string, readonly [string, FlagSchema]>,
613
- ): string | undefined {
614
- let bestName: string | undefined;
615
- let bestDist = Number.POSITIVE_INFINITY;
616
- const threshold = Math.max(2, Math.floor(input.length / 2));
617
-
618
- for (const key of lookup.keys()) {
619
- const entry = lookup.get(key);
620
- if (entry === undefined) continue;
621
- const [canonicalName, schema] = entry;
622
- const alias = schema.aliases.find((candidate) => candidate.name === key);
623
-
624
- // Only suggest canonical names or visible long aliases.
625
- if (key.length < 2) continue;
626
- if (key !== canonicalName && alias?.hidden) continue;
627
-
628
- const dist = levenshtein(input, key);
629
- if (dist < bestDist && dist <= threshold) {
630
- bestDist = dist;
631
- bestName = key;
632
- }
633
- }
634
-
635
- return bestName;
636
- }
637
-
638
- /**
639
- * Classic Levenshtein distance using a single-row DP approach.
640
- *
641
- * @param a - First string
642
- * @param b - Second string
643
- * @returns Edit distance between `a` and `b`
644
- */
645
- function levenshtein(a: string, b: string): number {
646
- if (a === b) return 0;
647
- if (a.length === 0) return b.length;
648
- if (b.length === 0) return a.length;
649
-
650
- // Ensure `short` is the shorter string for the single-row optimisation
651
- const short = a.length <= b.length ? a : b;
652
- const long = a.length <= b.length ? b : a;
653
-
654
- const aLen = short.length;
655
- const bLen = long.length;
656
-
657
- // Previous row of distances
658
- const row = Array.from({ length: aLen + 1 }, (_, i) => i);
659
-
660
- for (let j = 1; j <= bLen; j++) {
661
- let prev = row[0] ?? 0;
662
- row[0] = j;
663
- for (let k = 1; k <= aLen; k++) {
664
- const cost = short.charAt(k - 1) === long.charAt(j - 1) ? 0 : 1;
665
- const current = Math.min(
666
- (row[k] ?? 0) + 1, // deletion
667
- (row[k - 1] ?? 0) + 1, // insertion
668
- prev + cost, // substitution
669
- );
670
- prev = row[k] ?? 0;
671
- row[k] = current;
672
- }
673
- }
674
-
675
- return row[aLen] ?? 0;
676
- }
677
-
678
- // --- Exports
679
-
680
- export type { ParseResult, Token };
681
- export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };