@kjanat/dreamcli 3.0.1 → 4.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 (137) hide show
  1. package/CHANGELOG.md +962 -1
  2. package/README.md +7 -3
  3. package/dist/core/cli/builtins.d.mts +47 -0
  4. package/dist/core/cli/builtins.mjs +135 -0
  5. package/dist/core/cli/compiled.d.mts +29 -0
  6. package/dist/core/cli/compiled.mjs +76 -0
  7. package/dist/core/cli/dispatch.d.mts +9 -85
  8. package/dist/core/cli/help-links.d.mts +2 -14
  9. package/dist/core/cli/index.d.mts +282 -101
  10. package/dist/core/cli/index.mjs +497 -264
  11. package/dist/core/cli/planner.d.mts +13 -86
  12. package/dist/core/cli/planner.mjs +47 -30
  13. package/dist/core/cli/plugin.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +1 -1
  15. package/dist/core/cli/reserved-flags.d.mts +1 -0
  16. package/dist/core/cli/reserved-flags.mjs +158 -0
  17. package/dist/core/cli/root-help.d.mts +1 -47
  18. package/dist/core/cli/root-help.mjs +37 -47
  19. package/dist/core/cli/root-output-flags.d.mts +1 -0
  20. package/dist/core/cli/root-output-flags.mjs +169 -0
  21. package/dist/core/cli/root-surface.d.mts +1 -68
  22. package/dist/core/cli/root-surface.mjs +2 -2
  23. package/dist/core/cli/runtime-preflight.d.mts +1 -199
  24. package/dist/core/cli/runtime-preflight.mjs +67 -17
  25. package/dist/core/completion/index.d.mts +2 -2
  26. package/dist/core/completion/shells/bash.d.mts +0 -1
  27. package/dist/core/completion/shells/bash.mjs +2 -1
  28. package/dist/core/completion/shells/fish.d.mts +0 -1
  29. package/dist/core/completion/shells/fish.mjs +2 -1
  30. package/dist/core/completion/shells/powershell.d.mts +0 -1
  31. package/dist/core/completion/shells/powershell.mjs +2 -1
  32. package/dist/core/completion/shells/shared.d.mts +3 -114
  33. package/dist/core/completion/shells/shared.mjs +9 -39
  34. package/dist/core/completion/shells/zsh.d.mts +0 -1
  35. package/dist/core/completion/shells/zsh.mjs +2 -1
  36. package/dist/core/config/index.d.mts +3 -3
  37. package/dist/core/config/index.mjs +2 -2
  38. package/dist/core/config/package-json.d.mts +2 -33
  39. package/dist/core/config/package-json.mjs +1 -34
  40. package/dist/core/errors/index.d.mts +7 -7
  41. package/dist/core/execution/index.d.mts +1 -48
  42. package/dist/core/execution/index.mjs +42 -27
  43. package/dist/core/help/ansi.d.mts +0 -11
  44. package/dist/core/help/index.d.mts +3 -35
  45. package/dist/core/help/index.mjs +29 -6
  46. package/dist/core/help/theme.d.mts +1 -21
  47. package/dist/core/json-schema/index.d.mts +279 -10
  48. package/dist/core/json-schema/index.mjs +482 -237
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +79 -7
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +40 -6
  51. package/dist/core/output/activity.d.mts +1 -193
  52. package/dist/core/output/activity.mjs +1 -1
  53. package/dist/core/output/bind.d.mts +1 -37
  54. package/dist/core/output/contracts.d.mts +7 -13
  55. package/dist/core/output/contracts.mjs +1 -1
  56. package/dist/core/output/display-value.d.mts +1 -19
  57. package/dist/core/output/index.d.mts +5 -187
  58. package/dist/core/output/index.mjs +44 -9
  59. package/dist/core/output/renderers.d.mts +1 -45
  60. package/dist/core/output/writer.d.mts +0 -1
  61. package/dist/core/parse/index.d.mts +27 -5
  62. package/dist/core/parse/index.mjs +350 -227
  63. package/dist/core/parse/occurrences.d.mts +89 -0
  64. package/dist/core/parse/occurrences.mjs +114 -0
  65. package/dist/core/prompt/index.d.mts +3 -3
  66. package/dist/core/read-flags/index.d.mts +150 -0
  67. package/dist/core/read-flags/index.mjs +217 -0
  68. package/dist/core/resolve/args.d.mts +35 -4
  69. package/dist/core/resolve/args.mjs +132 -55
  70. package/dist/core/resolve/coerce.d.mts +66 -9
  71. package/dist/core/resolve/coerce.mjs +834 -270
  72. package/dist/core/resolve/config.d.mts +1 -10
  73. package/dist/core/resolve/contracts.d.mts +67 -44
  74. package/dist/core/resolve/errors.mjs +29 -21
  75. package/dist/core/resolve/flags.d.mts +36 -9
  76. package/dist/core/resolve/flags.mjs +129 -151
  77. package/dist/core/resolve/index.d.mts +8 -6
  78. package/dist/core/resolve/index.mjs +51 -18
  79. package/dist/core/resolve/path-checks.d.mts +47 -0
  80. package/dist/core/resolve/path-checks.mjs +102 -0
  81. package/dist/core/resolve/redaction.d.mts +12 -0
  82. package/dist/core/resolve/redaction.mjs +14 -0
  83. package/dist/core/resolve/stages.d.mts +85 -0
  84. package/dist/core/resolve/stages.mjs +170 -0
  85. package/dist/core/resolve/standard.d.mts +1 -24
  86. package/dist/core/resolve/standard.mjs +141 -43
  87. package/dist/core/schema/activity.d.mts +16 -16
  88. package/dist/core/schema/arg.d.mts +849 -71
  89. package/dist/core/schema/arg.mjs +727 -54
  90. package/dist/core/schema/brand.d.mts +17 -0
  91. package/dist/core/schema/cardinality.d.mts +301 -0
  92. package/dist/core/schema/cardinality.mjs +514 -0
  93. package/dist/core/schema/command.d.mts +173 -119
  94. package/dist/core/schema/command.mjs +305 -42
  95. package/dist/core/schema/flag.d.mts +515 -173
  96. package/dist/core/schema/flag.mjs +576 -78
  97. package/dist/core/schema/index.d.mts +11 -8
  98. package/dist/core/schema/index.mjs +10 -0
  99. package/dist/core/schema/middleware.d.mts +15 -12
  100. package/dist/core/schema/number-constraints.d.mts +5 -5
  101. package/dist/core/schema/prompt.d.mts +4 -4
  102. package/dist/core/schema/provenance.d.mts +99 -0
  103. package/dist/core/schema/provenance.mjs +28 -0
  104. package/dist/core/schema/run.d.mts +21 -60
  105. package/dist/core/schema/source.d.mts +179 -0
  106. package/dist/core/schema/source.mjs +206 -0
  107. package/dist/core/schema/standard.d.mts +12 -19
  108. package/dist/core/schema/stdin.d.mts +87 -0
  109. package/dist/core/schema/stdin.mjs +91 -0
  110. package/dist/core/schema/string-constraints.d.mts +16 -5
  111. package/dist/core/schema/string-constraints.mjs +18 -1
  112. package/dist/core/schema/value-parsers.d.mts +81 -9
  113. package/dist/core/schema/value-parsers.mjs +19 -1
  114. package/dist/core/schema/value.d.mts +242 -0
  115. package/dist/core/schema/value.mjs +573 -0
  116. package/dist/core/testkit/index.d.mts +30 -3
  117. package/dist/core/testkit/index.mjs +40 -26
  118. package/dist/index.d.mts +21 -16
  119. package/dist/index.mjs +10 -6
  120. package/dist/runtime/adapter.d.mts +3 -3
  121. package/dist/runtime/deno.d.mts +3 -3
  122. package/dist/runtime/detect.d.mts +2 -2
  123. package/dist/runtime/node.d.mts +3 -3
  124. package/dist/runtime/paths.d.mts +1 -31
  125. package/dist/runtime.d.mts +4 -4
  126. package/dist/strings.d.mts +1 -16
  127. package/dist/testkit.d.mts +2 -2
  128. package/dist/testkit.mjs +1 -1
  129. package/dist/version.d.mts +0 -13
  130. package/dist/version.mjs +2 -2
  131. package/dreamcli.schema.json +368 -78
  132. package/examples/interactive.ts +6 -5
  133. package/package.json +12 -11
  134. package/skills/cli-creation/SKILL.md +72 -16
  135. package/skills/cli-creation/references/pattern-cookbook.md +169 -11
  136. package/dist/core/resolve/property.d.mts +0 -51
  137. package/dist/core/resolve/property.mjs +0 -53
@@ -1,7 +1,12 @@
1
1
  import { ParseError } from "../errors/index.mjs";
2
- import { describeNumberConstraintViolation, validateNumberConstraints } from "../schema/number-constraints.mjs";
3
- import { describeStringConstraintViolation, validateStringConstraints } from "../schema/string-constraints.mjs";
2
+ import { describeNumberConstraintViolation } from "../schema/number-constraints.mjs";
3
+ import { describeStringConstraintViolation, stringConstraintDetails } from "../schema/string-constraints.mjs";
4
+ import { argValueSchema, decodeValue, flagValueSchema } from "../schema/value.mjs";
5
+ import { argCardinality, flagCardinality, isCollection, splitEntryPair } from "../schema/cardinality.mjs";
6
+ import { stdinReadsOnDash } from "../schema/stdin.mjs";
4
7
  import { getFlagAliasNames, getFlagNegatedName } from "../schema/flag.mjs";
8
+ import "../schema/index.mjs";
9
+ import { INCREMENT_OCCURRENCE, NEGATED_OCCURRENCE, STDIN_OCCURRENCE, occurrenceValue, projectOccurrences } from "./occurrences.mjs";
5
10
  //#region src/core/parse/index.ts
6
11
  /**
7
12
  * Argv tokenization and parsing against command schemas.
@@ -104,6 +109,19 @@ function includesBeforeSeparator(argv, token) {
104
109
  return false;
105
110
  }
106
111
  /**
112
+ * Whether argv asks for help before the `--` end-of-options separator.
113
+ *
114
+ * Help renders ahead of flag validation everywhere: a command short-circuits to
115
+ * its help text before `parse()` runs, and the root does the same before
116
+ * dispatch, so a malformed flag value never hides the text explaining the flags.
117
+ *
118
+ * @param argv - Raw argument strings.
119
+ * @returns `true` if `--help` or `-h` occurs before any `--` separator.
120
+ */
121
+ function requestsHelp(argv) {
122
+ return includesBeforeSeparator(argv, "--help") || includesBeforeSeparator(argv, "-h");
123
+ }
124
+ /**
107
125
  * Remove every occurrence of `token` that appears before the `--` end-of-options
108
126
  * separator, leaving post-separator literals untouched.
109
127
  *
@@ -194,37 +212,83 @@ function buildFlagLookup(flags, options) {
194
212
  return lookup;
195
213
  }
196
214
  /**
215
+ * The occurrence list of one logical flag, started on its first occurrence.
216
+ *
217
+ * @param occurrences - Per-parse accumulator keyed by canonical name
218
+ * @param name - Canonical flag name
219
+ * @param schema - Flag schema the occurrences belong to
220
+ * @returns The flag's list
221
+ */
222
+ function occurrencesOf(occurrences, name, schema) {
223
+ const existing = occurrences.get(name);
224
+ if (existing !== void 0) return existing;
225
+ const started = {
226
+ schema,
227
+ occurrences: [],
228
+ counted: 0
229
+ };
230
+ occurrences.set(name, started);
231
+ return started;
232
+ }
233
+ /**
197
234
  * Record one CLI occurrence of a logical flag and enforce its duplicate
198
235
  * policy.
199
236
  *
200
237
  * @param occurrences - Per-parse accumulator keyed by canonical name
201
238
  * @param name - Canonical flag name
202
239
  * @param schema - Flag schema (read for {@link FlagSchema.duplicates})
203
- * @param value - The occurrence's raw value (or the boolean it implies)
240
+ * @param reported - The occurrence's raw value (or the boolean it implies)
204
241
  * @param displayName - User-facing spelling for error messages
205
- * @returns `true` when the occurrence should be applied; `false` when the
206
- * `'first'` policy suppresses it (the token is still consumed)
242
+ * @param items - Lazily builds what the occurrence contributes when policy
243
+ * keeps it
207
244
  * @throws ParseError `DUPLICATE_FLAG` on a repeat under the `'error'` policy
208
245
  */
209
- function recordFlagOccurrence(occurrences, name, schema, value, displayName) {
210
- const record = occurrences.get(name) ?? {
211
- count: 0,
212
- values: []
213
- };
214
- record.count += 1;
215
- record.values.push(value);
216
- occurrences.set(name, record);
217
- if (record.count === 1) return true;
218
- if (schema.duplicates === "error") throw new ParseError(`Flag --${name} may only be specified once`, {
246
+ function recordFlagOccurrence(occurrences, name, schema, reported, displayName, items) {
247
+ const record = occurrencesOf(occurrences, name, schema);
248
+ record.counted += 1;
249
+ if (record.counted > 1 && schema.duplicates === "error") throw new ParseError(`Flag --${name} may only be specified once`, {
219
250
  code: "DUPLICATE_FLAG",
220
251
  details: {
221
252
  flag: name,
222
253
  input: displayName,
223
- count: record.count,
224
- values: [...record.values]
254
+ count: record.counted,
255
+ values: [...record.occurrences.filter((entry) => entry.policed).map((entry) => entry.reported), reported]
225
256
  }
226
257
  });
227
- return schema.duplicates !== "first";
258
+ if (record.counted > 1 && schema.duplicates === "first") return;
259
+ record.occurrences.push({
260
+ policed: true,
261
+ reported,
262
+ items: items()
263
+ });
264
+ }
265
+ /**
266
+ * Record one bare occurrence of a count flag.
267
+ *
268
+ * A bare `-v` raises the count rather than supplying a value, and the duplicate
269
+ * policy governs supplied values, so the increment stays outside it.
270
+ *
271
+ * @param occurrences - Per-parse accumulator keyed by canonical name
272
+ * @param name - Canonical flag name
273
+ * @param schema - Flag schema the occurrence belongs to
274
+ */
275
+ function recordCountIncrement(occurrences, name, schema) {
276
+ occurrencesOf(occurrences, name, schema).occurrences.push({
277
+ policed: false,
278
+ reported: void 0,
279
+ items: [INCREMENT_OCCURRENCE]
280
+ });
281
+ }
282
+ /**
283
+ * Project every flag's occurrences onto the values a parse result carries.
284
+ *
285
+ * @param occurrences - Per-parse accumulator keyed by canonical name
286
+ * @returns Flag values keyed by canonical name, in first-occurrence order
287
+ */
288
+ function projectFlags(occurrences) {
289
+ const flags = {};
290
+ for (const [name, record] of occurrences) flags[name] = projectOccurrences(flagCardinality(record.schema), record.occurrences.flatMap((occurrence) => occurrence.items));
291
+ return flags;
228
292
  }
229
293
  /**
230
294
  * Whether a flag kind expects a value argument (vs. being a bare boolean).
@@ -236,196 +300,248 @@ function flagExpectsValue(schema) {
236
300
  return schema.kind !== "boolean" && schema.kind !== "count";
237
301
  }
238
302
  /**
239
- * Coerce a raw string to the flag's declared kind.
303
+ * Whether a token is the stdin sentinel for an input that reads on `-`.
304
+ *
305
+ * The sentinel names the source, not the value, so it passes through the parse
306
+ * boundary untouched and the resolver reads the buffer in its place. Without
307
+ * this a `-` handed to `flag.number().stdin()` would be rejected here as a
308
+ * malformed number before resolution ever saw it.
309
+ *
310
+ * @param raw - Raw token from argv.
311
+ * @param stdin - The input's stdin axis.
312
+ * @returns `true` when the token selects stdin.
313
+ */
314
+ function isStdinSentinel(raw, stdin) {
315
+ return raw === "-" && stdin !== void 0 && stdinReadsOnDash(stdin);
316
+ }
317
+ /**
318
+ * Coerce one raw CLI token to what the flag's value axis declares.
240
319
  *
241
320
  * @param flagName - Canonical flag name (for error messages)
242
321
  * @param raw - Raw string value from argv
243
322
  * @param schema - {@link FlagSchema} declaring the expected kind
244
- * @returns Coerced value matching the schema's kind
323
+ * @param displayName - Spelling the user typed
324
+ * @returns The coerced token: a value, an element, or a `[key, value]` pair
245
325
  * @throws ParseError on type mismatch
246
326
  */
247
327
  function coerceFlagValue(flagName, raw, schema, displayName = `--${flagName}`) {
248
- switch (schema.kind) {
249
- case "string": {
250
- const violation = validateStringConstraints(raw, schema.stringConstraints);
251
- if (violation !== void 0) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}: ${describeStringConstraintViolation(violation)}`, {
252
- code: "INVALID_VALUE",
253
- details: {
254
- flag: flagName,
255
- input: displayName,
256
- value: raw,
257
- expected: "string",
258
- constraint: violation.kind,
259
- ..."bound" in violation ? { bound: violation.bound } : {},
260
- ..."pattern" in violation ? { pattern: violation.pattern } : {}
261
- }
262
- });
263
- return raw;
328
+ return occurrenceValue(flagTokenOccurrence(flagName, raw, schema, displayName));
329
+ }
330
+ /**
331
+ * Read one raw CLI token of a flag as the occurrence it contributes.
332
+ *
333
+ * The cardinality axis decides what a token IS: one value, one element of a
334
+ * collection, one entry of a record, or an explicit count. The value axis then
335
+ * decides what that token means. A `-` names the stdin source, so it holds its
336
+ * position without being decoded.
337
+ *
338
+ * @param flagName - Canonical flag name (for error messages)
339
+ * @param raw - Raw string value from argv
340
+ * @param schema - {@link FlagSchema} declaring the expected kind
341
+ * @param displayName - Spelling the user typed
342
+ * @returns The occurrence the token contributes
343
+ * @throws ParseError on type mismatch
344
+ */
345
+ function flagTokenOccurrence(flagName, raw, schema, displayName) {
346
+ if (isStdinSentinel(raw, schema.stdin)) return STDIN_OCCURRENCE;
347
+ const cardinality = flagCardinality(schema);
348
+ if (cardinality.kind === "count") return {
349
+ kind: "value",
350
+ value: coerceCountToken(flagName, raw, displayName)
351
+ };
352
+ if (cardinality.kind === "entries") {
353
+ const [key, value] = coerceEntryToken(flagName, raw, schema, displayName);
354
+ return {
355
+ kind: "entry",
356
+ key,
357
+ value
358
+ };
359
+ }
360
+ return {
361
+ kind: "value",
362
+ value: coerceElementToken(flagName, raw, schema, displayName)
363
+ };
364
+ }
365
+ /** Decode one token through the flag's element value axis. */
366
+ function coerceElementToken(flagName, raw, schema, displayName) {
367
+ const decoded = decodeValue(flagValueSchema(schema), raw, "token");
368
+ if (decoded.ok) return decoded.value;
369
+ throw flagValueError(flagName, displayName, raw, decoded.failure);
370
+ }
371
+ /** Read an explicit count token such as `--verbose=2`. */
372
+ function coerceCountToken(flagName, raw, displayName) {
373
+ const count = raw.trim() === "" ? NaN : Number(raw);
374
+ if (!Number.isInteger(count) || count < 0) throw new ParseError(`Invalid count value '${raw}' for flag ${displayName}. Use a non-negative integer`, {
375
+ code: "INVALID_VALUE",
376
+ details: {
377
+ flag: flagName,
378
+ input: displayName,
379
+ value: raw,
380
+ expected: "count"
264
381
  }
265
- case "number": {
266
- const n = Number(raw);
267
- if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}`, {
382
+ });
383
+ return count;
384
+ }
385
+ /** Read one `KEY=VALUE` token and decode its value through the element value axis. */
386
+ function coerceEntryToken(flagName, raw, schema, displayName) {
387
+ const pair = splitEntryPair(raw);
388
+ if (pair === void 0) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Use KEY=VALUE`, {
389
+ code: "INVALID_VALUE",
390
+ details: {
391
+ flag: flagName,
392
+ input: displayName,
393
+ value: raw,
394
+ expected: "key=value"
395
+ }
396
+ });
397
+ return [pair[0], coerceElementToken(flagName, pair[1], schema, displayName)];
398
+ }
399
+ /** Map a shared value-layer failure to a subject-specific parse error. @internal */
400
+ function valueParseError(subject, raw, failure) {
401
+ const details = {
402
+ ...subject.details,
403
+ value: raw
404
+ };
405
+ switch (failure.kind) {
406
+ case "type":
407
+ if (failure.expected === "number") return new ParseError(`Invalid number value '${raw}' for ${subject.label}`, {
268
408
  code: "INVALID_VALUE",
269
409
  details: {
270
- flag: flagName,
271
- input: displayName,
272
- value: raw,
410
+ ...details,
273
411
  expected: "number"
274
412
  }
275
413
  });
276
- const violation = validateNumberConstraints(n, schema.numberConstraints);
277
- if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for flag ${displayName}: ${describeNumberConstraintViolation(violation)}`, {
414
+ if (failure.expected === "boolean") return new ParseError(`Invalid boolean value '${raw}' for ${subject.label}. Use true/false or 1/0`, {
278
415
  code: "INVALID_VALUE",
279
416
  details: {
280
- flag: flagName,
281
- input: displayName,
282
- value: raw,
283
- expected: "number",
284
- constraint: violation.kind,
285
- ..."bound" in violation ? { bound: violation.bound } : {}
417
+ ...details,
418
+ expected: "boolean"
286
419
  }
287
420
  });
288
- return n;
289
- }
290
- case "boolean":
291
- if (raw === "true" || raw === "1") return true;
292
- if (raw === "false" || raw === "0") return false;
293
- throw new ParseError(`Invalid boolean value '${raw}' for flag ${displayName}. Use true/false or 1/0`, {
421
+ return new ParseError(`Invalid value '${raw}' for ${subject.label}`, {
294
422
  code: "INVALID_VALUE",
295
423
  details: {
296
- flag: flagName,
297
- input: displayName,
298
- value: raw,
299
- expected: "boolean"
424
+ ...details,
425
+ expected: "string"
300
426
  }
301
427
  });
302
428
  case "enum": {
303
- const allowed = schema.enumValues;
304
- if (allowed === void 0) throw new ParseError(`Enum flag --${flagName} is misconfigured: no allowed values declared`, {
429
+ const allowed = failure.enumValues;
430
+ if (allowed === void 0) return new ParseError(`${subject.enumLabel} is misconfigured: no allowed values declared`, {
305
431
  code: "INVALID_SCHEMA",
306
- details: {
307
- flag: flagName,
308
- kind: "enum",
309
- missing: "enumValues"
310
- }
432
+ details: subject.enumDetails
311
433
  });
312
- if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Allowed: ${allowed.join(", ")}`, {
434
+ return new ParseError(`Invalid value '${raw}' for ${subject.label}. Allowed: ${allowed.join(", ")}`, {
313
435
  code: "INVALID_VALUE",
314
436
  details: {
315
- flag: flagName,
316
- input: displayName,
317
- value: raw,
437
+ ...details,
318
438
  allowed
319
439
  }
320
440
  });
321
- return raw;
322
441
  }
323
- case "array":
324
- if (schema.elementSchema) return coerceFlagValue(flagName, raw, schema.elementSchema);
325
- return raw;
326
- case "custom":
327
- if (!schema.parseFn) return raw;
328
- try {
329
- return schema.parseFn(raw);
330
- } catch (err) {
331
- if (err instanceof ParseError) throw err;
332
- throw new ParseError(`Failed to parse flag ${displayName}: ${err instanceof Error ? err.message : String(err)}`, {
333
- code: "INVALID_VALUE",
334
- details: {
335
- flag: flagName,
336
- input: displayName,
337
- value: raw
338
- },
339
- cause: err
340
- });
442
+ case "string-constraint": return new ParseError(`Invalid value '${raw}' for ${subject.label}: ${describeStringConstraintViolation(failure.violation)}`, {
443
+ code: "INVALID_VALUE",
444
+ details: {
445
+ ...details,
446
+ expected: "string",
447
+ ...stringConstraintDetails(failure.violation)
341
448
  }
342
- case "count": {
343
- const n = raw.trim() === "" ? NaN : Number(raw);
344
- if (!Number.isInteger(n) || n < 0) throw new ParseError(`Invalid count value '${raw}' for flag ${displayName}. Use a non-negative integer`, {
449
+ });
450
+ case "number-constraint": return new ParseError(`Invalid number value '${raw}' for ${subject.label}: ${describeNumberConstraintViolation(failure.violation)}`, {
451
+ code: "INVALID_VALUE",
452
+ details: {
453
+ ...details,
454
+ expected: "number",
455
+ constraint: failure.violation.kind,
456
+ ..."bound" in failure.violation ? { bound: failure.violation.bound } : {}
457
+ }
458
+ });
459
+ case "thrown": {
460
+ if (failure.error instanceof ParseError) return failure.error;
461
+ const message = failure.error instanceof Error ? failure.error.message : String(failure.error);
462
+ return new ParseError(`Failed to parse ${subject.label}: ${message}`, {
345
463
  code: "INVALID_VALUE",
346
- details: {
347
- flag: flagName,
348
- input: displayName,
349
- value: raw,
350
- expected: "count"
351
- }
464
+ details,
465
+ cause: failure.error
352
466
  });
353
- return n;
354
467
  }
355
- case "keyValue": return parseKeyValuePair(flagName, raw, displayName);
356
468
  }
357
469
  }
470
+ /** Name the flag a rejected value belonged to. */
471
+ function flagValueError(flagName, displayName, raw, failure) {
472
+ return valueParseError({
473
+ details: {
474
+ flag: flagName,
475
+ input: displayName
476
+ },
477
+ label: `flag ${displayName}`,
478
+ enumDetails: {
479
+ flag: flagName,
480
+ kind: "enum",
481
+ missing: "enumValues"
482
+ },
483
+ enumLabel: `Enum flag --${flagName}`
484
+ }, raw, failure);
485
+ }
358
486
  /**
359
- * Coerce a raw string to the arg's declared kind.
487
+ * Read one raw positional token as the occurrence it contributes.
488
+ *
489
+ * A `-` names the stdin source, so it holds its position without being decoded.
360
490
  *
361
491
  * @param argName - Positional arg name (for error messages)
362
492
  * @param raw - Raw string value from argv
363
493
  * @param schema - {@link ArgSchema} declaring the expected kind
364
- * @returns Coerced value matching the schema's kind
494
+ * @returns The occurrence the token contributes
365
495
  * @throws ParseError on type mismatch or custom parse failure
366
496
  */
367
- function coerceArgValue(argName, raw, schema) {
368
- switch (schema.kind) {
369
- case "string": return raw;
370
- case "number": {
371
- const n = Number(raw);
372
- if (Number.isNaN(n)) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>`, {
373
- code: "INVALID_VALUE",
374
- details: {
375
- arg: argName,
376
- value: raw,
377
- expected: "number"
378
- }
379
- });
380
- const violation = validateNumberConstraints(n, schema.numberConstraints);
381
- if (violation !== void 0) throw new ParseError(`Invalid number value '${raw}' for argument <${argName}>: ${describeNumberConstraintViolation(violation)}`, {
382
- code: "INVALID_VALUE",
383
- details: {
384
- arg: argName,
385
- value: raw,
386
- expected: "number",
387
- constraint: violation.kind,
388
- ..."bound" in violation ? { bound: violation.bound } : {}
389
- }
390
- });
391
- return n;
392
- }
393
- case "enum": {
394
- const allowed = schema.enumValues;
395
- if (allowed === void 0) throw new ParseError(`Enum argument <${argName}> is misconfigured: no allowed values declared`, {
396
- code: "INVALID_SCHEMA",
397
- details: {
398
- arg: argName,
399
- kind: "enum",
400
- missing: "enumValues"
401
- }
402
- });
403
- if (!allowed.includes(raw)) throw new ParseError(`Invalid value '${raw}' for argument <${argName}>. Allowed: ${allowed.join(", ")}`, {
404
- code: "INVALID_VALUE",
405
- details: {
406
- arg: argName,
407
- value: raw,
408
- allowed
409
- }
410
- });
411
- return raw;
412
- }
413
- case "custom":
414
- if (!schema.parseFn) return raw;
415
- try {
416
- return schema.parseFn(raw);
417
- } catch (err) {
418
- if (err instanceof ParseError) throw err;
419
- throw new ParseError(`Failed to parse argument <${argName}>: ${err instanceof Error ? err.message : String(err)}`, {
420
- code: "INVALID_VALUE",
421
- details: {
422
- arg: argName,
423
- value: raw
424
- },
425
- cause: err
426
- });
497
+ function argTokenOccurrence(argName, raw, schema) {
498
+ if (isStdinSentinel(raw, schema.stdin)) return STDIN_OCCURRENCE;
499
+ if (argCardinality(schema).kind === "entries") {
500
+ const pair = splitEntryPair(raw);
501
+ if (pair === void 0) throw new ParseError(`Invalid value '${raw}' for argument <${argName}>. Use KEY=VALUE`, {
502
+ code: "INVALID_VALUE",
503
+ details: {
504
+ arg: argName,
505
+ value: raw,
506
+ expected: "key=value"
427
507
  }
508
+ });
509
+ return {
510
+ kind: "entry",
511
+ key: pair[0],
512
+ value: decodeArgToken(argName, pair[1], schema)
513
+ };
428
514
  }
515
+ return {
516
+ kind: "value",
517
+ value: decodeArgToken(argName, raw, schema)
518
+ };
519
+ }
520
+ /** Decode one token through the arg's element value axis. */
521
+ function decodeArgToken(argName, raw, schema) {
522
+ const decoded = decodeValue(argValueSchema(schema), raw, "token");
523
+ if (decoded.ok) return decoded.value;
524
+ throw argValueError(argName, raw, decoded.failure);
525
+ }
526
+ /**
527
+ * Name the positional argument a rejected value belonged to.
528
+ *
529
+ * @param argName - Positional arg name.
530
+ * @param raw - Raw string value from argv.
531
+ * @param failure - What the value layer rejected.
532
+ * @returns The error to throw.
533
+ */
534
+ function argValueError(argName, raw, failure) {
535
+ return valueParseError({
536
+ details: { arg: argName },
537
+ label: `argument <${argName}>`,
538
+ enumDetails: {
539
+ arg: argName,
540
+ kind: "enum",
541
+ missing: "enumValues"
542
+ },
543
+ enumLabel: `Enum argument <${argName}>`
544
+ }, raw, failure);
429
545
  }
430
546
  /**
431
547
  * Parse tokenized argv against a command schema.
@@ -449,7 +565,6 @@ function coerceArgValue(argName, raw, schema) {
449
565
  function parse(schema, argv, options) {
450
566
  const tokens = tokenize(argv);
451
567
  const flagLookup = buildFlagLookup(schema.flags, options);
452
- const flags = {};
453
568
  const positionals = [];
454
569
  const occurrences = /* @__PURE__ */ new Map();
455
570
  let i = 0;
@@ -466,14 +581,15 @@ function parse(schema, argv, options) {
466
581
  continue;
467
582
  }
468
583
  if (token.kind === "long-flag") {
469
- i = parseLongFlag(token, tokens, i, flagLookup, flags, occurrences);
584
+ i = parseLongFlag(token, tokens, i, flagLookup, occurrences);
470
585
  continue;
471
586
  }
472
- i = parseShortFlags(token, tokens, i, flagLookup, flags, occurrences);
587
+ i = parseShortFlags(token, tokens, i, flagLookup, occurrences);
473
588
  }
589
+ const args = mapPositionals(schema.args, positionals);
474
590
  return {
475
- flags,
476
- args: mapPositionals(schema.args, positionals)
591
+ flags: projectFlags(occurrences),
592
+ args
477
593
  };
478
594
  }
479
595
  /**
@@ -483,11 +599,10 @@ function parse(schema, argv, options) {
483
599
  * @param tokens - Full token array (for lookahead)
484
600
  * @param startIdx - Current index of `token` in the array
485
601
  * @param flagLookup - Spelling → {@link FlagLookupEntry} map from {@link buildFlagLookup}
486
- * @param flags - Mutable accumulator for resolved flag values
487
- * @param occurrences - Per-parse duplicate-occurrence accumulator
602
+ * @param occurrences - Per-parse occurrence accumulator
488
603
  * @returns Next index to continue parsing from
489
604
  */
490
- function parseLongFlag(token, tokens, startIdx, flagLookup, flags, occurrences) {
605
+ function parseLongFlag(token, tokens, startIdx, flagLookup, occurrences) {
491
606
  const entry = flagLookup.get(token.name);
492
607
  if (!entry) {
493
608
  const suggestion = suggestFlag(token.name, flagLookup);
@@ -511,21 +626,23 @@ function parseLongFlag(token, tokens, startIdx, flagLookup, flags, occurrences)
511
626
  value: token.value
512
627
  }
513
628
  });
514
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, false, displayName)) flags[canonicalName] = false;
629
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, false, displayName, () => [NEGATED_OCCURRENCE]);
515
630
  return startIdx + 1;
516
631
  }
517
632
  if (!flagExpectsValue(flagSchema)) {
518
633
  if (token.value !== void 0) {
519
- const coerced = coerceFlagValue(canonicalName, token.value, flagSchema, displayName);
520
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, coerced, displayName)) flags[canonicalName] = coerced;
521
- } else if (flagSchema.kind === "count") {
522
- const existing = flags[canonicalName];
523
- flags[canonicalName] = (typeof existing === "number" ? existing : 0) + 1;
524
- } else if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName)) flags[canonicalName] = true;
634
+ const item = flagTokenOccurrence(canonicalName, token.value, flagSchema, displayName);
635
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, occurrenceValue(item), displayName, () => [item]);
636
+ } else if (flagSchema.kind === "count") recordCountIncrement(occurrences, canonicalName, flagSchema);
637
+ else recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName, () => [{
638
+ kind: "value",
639
+ value: true
640
+ }]);
525
641
  return startIdx + 1;
526
642
  }
527
643
  if (token.value !== void 0) {
528
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, token.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, token.value);
644
+ const inlineValue = token.value;
645
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, inlineValue, displayName, () => flagTokenOccurrences(canonicalName, flagSchema, inlineValue, displayName));
529
646
  return startIdx + 1;
530
647
  }
531
648
  const nextToken = tokens[startIdx + 1];
@@ -537,7 +654,7 @@ function parseLongFlag(token, tokens, startIdx, flagLookup, flags, occurrences)
537
654
  kind: flagSchema.kind
538
655
  }
539
656
  });
540
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, nextToken.value, displayName);
657
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName, () => flagTokenOccurrences(canonicalName, flagSchema, nextToken.value, displayName));
541
658
  return startIdx + 2;
542
659
  }
543
660
  /**
@@ -547,11 +664,10 @@ function parseLongFlag(token, tokens, startIdx, flagLookup, flags, occurrences)
547
664
  * @param tokens - Full token array (for lookahead)
548
665
  * @param startIdx - Current index of `token` in the array
549
666
  * @param flagLookup - Spelling → {@link FlagLookupEntry} map from {@link buildFlagLookup}
550
- * @param flags - Mutable accumulator for resolved flag values
551
- * @param occurrences - Per-parse duplicate-occurrence accumulator
667
+ * @param occurrences - Per-parse occurrence accumulator
552
668
  * @returns Next index to continue parsing from
553
669
  */
554
- function parseShortFlags(token, tokens, startIdx, flagLookup, flags, occurrences) {
670
+ function parseShortFlags(token, tokens, startIdx, flagLookup, occurrences) {
555
671
  const { chars } = token;
556
672
  let nextIdx = startIdx + 1;
557
673
  for (let ci = 0; ci < chars.length; ci++) {
@@ -564,15 +680,16 @@ function parseShortFlags(token, tokens, startIdx, flagLookup, flags, occurrences
564
680
  const { name: canonicalName, schema: flagSchema } = entry;
565
681
  const displayName = `-${ch}`;
566
682
  if (!flagExpectsValue(flagSchema)) {
567
- if (flagSchema.kind === "count") {
568
- const existing = flags[canonicalName];
569
- flags[canonicalName] = (typeof existing === "number" ? existing : 0) + 1;
570
- } else if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName)) flags[canonicalName] = true;
683
+ if (flagSchema.kind === "count") recordCountIncrement(occurrences, canonicalName, flagSchema);
684
+ else recordFlagOccurrence(occurrences, canonicalName, flagSchema, true, displayName, () => [{
685
+ kind: "value",
686
+ value: true
687
+ }]);
571
688
  continue;
572
689
  }
573
690
  if (ci < chars.length - 1) {
574
691
  const inlineValue = chars.slice(ci + 1);
575
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, inlineValue, displayName)) setFlagValue(flags, canonicalName, flagSchema, inlineValue, displayName);
692
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, inlineValue, displayName, () => flagTokenOccurrences(canonicalName, flagSchema, inlineValue, displayName));
576
693
  break;
577
694
  }
578
695
  const nextToken = tokens[nextIdx];
@@ -584,56 +701,59 @@ function parseShortFlags(token, tokens, startIdx, flagLookup, flags, occurrences
584
701
  kind: flagSchema.kind
585
702
  }
586
703
  });
587
- if (recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName)) setFlagValue(flags, canonicalName, flagSchema, nextToken.value, displayName);
704
+ recordFlagOccurrence(occurrences, canonicalName, flagSchema, nextToken.value, displayName, () => flagTokenOccurrences(canonicalName, flagSchema, nextToken.value, displayName));
588
705
  nextIdx++;
589
706
  }
590
707
  return nextIdx;
591
708
  }
592
709
  /**
593
- * Set or accumulate a flag value, handling array flags specially.
710
+ * Read one value token of a flag as the occurrences it contributes.
711
+ *
712
+ * A collection keeps its CLI occurrences in the order they were typed, elements
713
+ * for `many` and `[key, value]` pairs for `entries`. Aggregation happens during
714
+ * resolution, where the stdin buffer an occurrence of `-` stands for is spliced
715
+ * into that order.
594
716
  *
595
- * @param flags - Mutable accumulator for resolved flag values
596
717
  * @param name - Canonical flag name
597
718
  * @param schema - {@link FlagSchema} declaring the expected kind
598
719
  * @param rawValue - Raw string value from argv
720
+ * @param displayName - Spelling the user typed
721
+ * @returns The occurrences the token contributes, in order
599
722
  */
600
- function setFlagValue(flags, name, schema, rawValue, displayName = `--${name}`) {
601
- if (schema.kind === "array") {
602
- const coercedParts = (schema.separator !== void 0 ? rawValue.split(schema.separator) : [rawValue]).filter((part) => schema.separator === void 0 || part.length > 0).map((part) => coerceFlagValue(name, part, schema, displayName));
603
- const existing = flags[name];
604
- if (Array.isArray(existing)) existing.push(...coercedParts);
605
- else flags[name] = coercedParts;
606
- return;
607
- }
608
- if (schema.kind === "keyValue") {
609
- const pair = parseKeyValuePair(name, rawValue, displayName);
610
- const existing = flags[name];
611
- flags[name] = Object.fromEntries([...isPlainRecord(existing) ? Object.entries(existing) : [], pair]);
612
- return;
613
- }
614
- flags[name] = coerceFlagValue(name, rawValue, schema, displayName);
723
+ function flagTokenOccurrences(name, schema, rawValue, displayName = `--${name}`) {
724
+ const cardinality = flagCardinality(schema);
725
+ if (!isCollection(cardinality)) return [flagTokenOccurrence(name, rawValue, schema, displayName)];
726
+ return splitCliToken(cardinality.cliSplit, rawValue, schema).map((part) => flagTokenOccurrence(name, part, schema, displayName));
615
727
  }
616
- /** Narrow to a mutable string-record accumulator (keyValue flags only ever store these). */
617
- function isPlainRecord(value) {
618
- return typeof value === "object" && value !== null && !Array.isArray(value);
728
+ /**
729
+ * Split one CLI token into the elements it carries.
730
+ *
731
+ * The stdin sentinel names a source rather than a value, so it stays one
732
+ * element whatever the split policy says.
733
+ *
734
+ * @param policy - The CLI split policy.
735
+ * @param raw - The raw token.
736
+ * @param schema - The input's schema, read for its stdin axis.
737
+ * @returns The token's elements.
738
+ */
739
+ function splitCliToken(policy, raw, schema) {
740
+ if (isStdinSentinel(raw, schema.stdin)) return [raw];
741
+ if (policy.format === "delimiter") return raw.split(policy.delimiter).filter((part) => part.length > 0);
742
+ return [raw];
619
743
  }
744
+ /** The CLI policy a single-value positional splits under: none at all. */
745
+ const WHOLE_TOKEN = { format: "whole" };
620
746
  /**
621
- * Split a `KEY=VALUE` token at the first `=`.
747
+ * The CLI split policy a cardinality carries.
748
+ *
749
+ * A scalar and a count have no elements to split into, so their tokens stay
750
+ * whole.
622
751
  *
623
- * @throws ParseError when the token has no `=` or an empty key.
752
+ * @param cardinality - How the input's values combine.
753
+ * @returns The policy each of its CLI tokens splits under.
624
754
  */
625
- function parseKeyValuePair(flagName, raw, displayName = `--${flagName}`) {
626
- const eq = raw.indexOf("=");
627
- if (eq <= 0) throw new ParseError(`Invalid value '${raw}' for flag ${displayName}. Use KEY=VALUE`, {
628
- code: "INVALID_VALUE",
629
- details: {
630
- flag: flagName,
631
- input: displayName,
632
- value: raw,
633
- expected: "key=value"
634
- }
635
- });
636
- return [raw.slice(0, eq), raw.slice(eq + 1)];
755
+ function cliSplitOf(cardinality) {
756
+ return cardinality.kind === "many" || cardinality.kind === "entries" ? cardinality.cliSplit : WHOLE_TOKEN;
637
757
  }
638
758
  /**
639
759
  * Map positional values to named args based on schema ordering.
@@ -647,15 +767,18 @@ function mapPositionals(argEntries, positionals) {
647
767
  const args = {};
648
768
  let posIdx = 0;
649
769
  for (const entry of argEntries) {
770
+ const cardinality = argCardinality(entry.schema);
771
+ const policy = cliSplitOf(cardinality);
650
772
  if (entry.schema.variadic) {
651
- const remaining = positionals.slice(posIdx);
652
- args[entry.name] = remaining.map((raw) => coerceArgValue(entry.name, raw, entry.schema));
773
+ const occurrences = positionals.slice(posIdx).flatMap((raw) => splitCliToken(policy, raw, { stdin: entry.schema.stdin }).map((part) => argTokenOccurrence(entry.name, part, entry.schema)));
774
+ args[entry.name] = projectOccurrences(cardinality, occurrences);
653
775
  posIdx = positionals.length;
654
776
  break;
655
777
  }
656
778
  const rawPositional = positionals[posIdx];
657
779
  if (rawPositional !== void 0) {
658
- args[entry.name] = coerceArgValue(entry.name, rawPositional, entry.schema);
780
+ const occurrences = splitCliToken(policy, rawPositional, { stdin: entry.schema.stdin }).map((part) => argTokenOccurrence(entry.name, part, entry.schema));
781
+ args[entry.name] = projectOccurrences(cardinality, occurrences);
659
782
  posIdx++;
660
783
  }
661
784
  }
@@ -724,4 +847,4 @@ function levenshtein(a, b) {
724
847
  return row[aLen] ?? 0;
725
848
  }
726
849
  //#endregion
727
- export { buildFlagLookup, camelToKebab, flagExpectsValue, includesBeforeSeparator, kebabToCamel, parse, stripBeforeSeparator, tokenize };
850
+ export { buildFlagLookup, camelToKebab, coerceFlagValue, flagExpectsValue, includesBeforeSeparator, kebabToCamel, parse, requestsHelp, stripBeforeSeparator, tokenize };