@kjanat/dreamcli 4.0.0-rc.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +5 -7
  2. package/dist/{runtime/adapter.d.mts → adapter-D0hbBNVB.d.mts} +2 -4
  3. package/dist/completion-D4mz6axB.mjs +6 -0
  4. package/dist/completion.d.mts +90 -0
  5. package/dist/completion.mjs +1 -0
  6. package/dist/config-B9ddC-Kb.mjs +1 -0
  7. package/dist/config.d.mts +2 -0
  8. package/dist/config.mjs +1 -0
  9. package/dist/core-Cp2w8vRq.mjs +17 -0
  10. package/dist/index-BziI2aKc.d.mts +5440 -0
  11. package/dist/index-DOfClfYR.d.mts +370 -0
  12. package/dist/index-DWsnGZlx.d.mts +831 -0
  13. package/dist/{core/cli/index.d.mts → index-DXROeDPC.d.mts} +116 -57
  14. package/dist/index-DndPmT8J.d.mts +275 -0
  15. package/dist/{core/json-schema/index.d.mts → index-DyoaS234.d.mts} +43 -34
  16. package/dist/index.d.mts +190 -41
  17. package/dist/index.mjs +1 -26
  18. package/dist/json-schema-C9SzZ7jY.mjs +52 -0
  19. package/dist/json-schema.d.mts +2 -0
  20. package/dist/json-schema.mjs +1 -0
  21. package/dist/package-json-BgE9YjjQ.mjs +3 -0
  22. package/dist/prompt.d.mts +48 -0
  23. package/dist/prompt.mjs +1 -0
  24. package/dist/rolldown-runtime-G4Kt5YOX.mjs +1 -0
  25. package/dist/runtime.d.mts +2 -6
  26. package/dist/runtime.mjs +1 -6
  27. package/dist/terminal-C8KTXjv5.mjs +6 -0
  28. package/dist/test-prompter-v__jT2yG.mjs +1 -0
  29. package/dist/testkit.d.mts +54 -6
  30. package/dist/testkit.mjs +1 -5
  31. package/dist/version.mjs +1 -7
  32. package/dreamcli.schema.json +697 -538
  33. package/package.json +29 -7
  34. package/skills/cli-creation/SKILL.md +16 -11
  35. package/CHANGELOG.md +0 -1116
  36. package/dist/core/cli/builtins.d.mts +0 -117
  37. package/dist/core/cli/builtins.mjs +0 -135
  38. package/dist/core/cli/compiled.d.mts +0 -66
  39. package/dist/core/cli/compiled.mjs +0 -76
  40. package/dist/core/cli/dispatch.d.mts +0 -115
  41. package/dist/core/cli/dispatch.mjs +0 -205
  42. package/dist/core/cli/help-links.d.mts +0 -27
  43. package/dist/core/cli/help-links.mjs +0 -41
  44. package/dist/core/cli/index.mjs +0 -1271
  45. package/dist/core/cli/planner.d.mts +0 -174
  46. package/dist/core/cli/planner.mjs +0 -323
  47. package/dist/core/cli/plugin.d.mts +0 -94
  48. package/dist/core/cli/plugin.mjs +0 -41
  49. package/dist/core/cli/propagate.d.mts +0 -39
  50. package/dist/core/cli/propagate.mjs +0 -57
  51. package/dist/core/cli/reserved-flags.d.mts +0 -19
  52. package/dist/core/cli/reserved-flags.mjs +0 -158
  53. package/dist/core/cli/root-help.d.mts +0 -53
  54. package/dist/core/cli/root-help.mjs +0 -221
  55. package/dist/core/cli/root-output-flags.d.mts +0 -74
  56. package/dist/core/cli/root-output-flags.mjs +0 -169
  57. package/dist/core/cli/root-surface.d.mts +0 -64
  58. package/dist/core/cli/root-surface.mjs +0 -28
  59. package/dist/core/cli/runtime-preflight.d.mts +0 -213
  60. package/dist/core/cli/runtime-preflight.mjs +0 -221
  61. package/dist/core/completion/index.d.mts +0 -76
  62. package/dist/core/completion/index.mjs +0 -90
  63. package/dist/core/completion/shells/bash.d.mts +0 -23
  64. package/dist/core/completion/shells/bash.mjs +0 -312
  65. package/dist/core/completion/shells/fish.d.mts +0 -19
  66. package/dist/core/completion/shells/fish.mjs +0 -164
  67. package/dist/core/completion/shells/powershell.d.mts +0 -13
  68. package/dist/core/completion/shells/powershell.mjs +0 -360
  69. package/dist/core/completion/shells/shared.d.mts +0 -164
  70. package/dist/core/completion/shells/shared.mjs +0 -147
  71. package/dist/core/completion/shells/zsh.d.mts +0 -23
  72. package/dist/core/completion/shells/zsh.mjs +0 -256
  73. package/dist/core/config/index.d.mts +0 -191
  74. package/dist/core/config/index.mjs +0 -285
  75. package/dist/core/config/package-json.d.mts +0 -179
  76. package/dist/core/config/package-json.mjs +0 -353
  77. package/dist/core/errors/index.d.mts +0 -125
  78. package/dist/core/errors/index.mjs +0 -87
  79. package/dist/core/execution/index.d.mts +0 -61
  80. package/dist/core/execution/index.mjs +0 -220
  81. package/dist/core/help/ansi.d.mts +0 -84
  82. package/dist/core/help/ansi.mjs +0 -121
  83. package/dist/core/help/index.d.mts +0 -149
  84. package/dist/core/help/index.mjs +0 -418
  85. package/dist/core/help/theme.d.mts +0 -86
  86. package/dist/core/help/theme.mjs +0 -69
  87. package/dist/core/json-schema/index.mjs +0 -1008
  88. package/dist/core/json-schema/meta-descriptions.generated.d.mts +0 -274
  89. package/dist/core/json-schema/meta-descriptions.generated.mjs +0 -136
  90. package/dist/core/output/activity.d.mts +0 -193
  91. package/dist/core/output/activity.mjs +0 -452
  92. package/dist/core/output/bind.d.mts +0 -37
  93. package/dist/core/output/bind.mjs +0 -56
  94. package/dist/core/output/contracts.d.mts +0 -82
  95. package/dist/core/output/contracts.mjs +0 -57
  96. package/dist/core/output/display-value.d.mts +0 -19
  97. package/dist/core/output/display-value.mjs +0 -32
  98. package/dist/core/output/index.d.mts +0 -344
  99. package/dist/core/output/index.mjs +0 -514
  100. package/dist/core/output/renderers.d.mts +0 -45
  101. package/dist/core/output/renderers.mjs +0 -46
  102. package/dist/core/output/writer.d.mts +0 -39
  103. package/dist/core/output/writer.mjs +0 -12
  104. package/dist/core/parse/index.d.mts +0 -178
  105. package/dist/core/parse/index.mjs +0 -850
  106. package/dist/core/parse/occurrences.d.mts +0 -90
  107. package/dist/core/parse/occurrences.mjs +0 -114
  108. package/dist/core/prompt/index.d.mts +0 -213
  109. package/dist/core/prompt/index.mjs +0 -348
  110. package/dist/core/read-flags/index.d.mts +0 -150
  111. package/dist/core/read-flags/index.mjs +0 -217
  112. package/dist/core/resolve/args.d.mts +0 -39
  113. package/dist/core/resolve/args.mjs +0 -182
  114. package/dist/core/resolve/coerce.d.mts +0 -79
  115. package/dist/core/resolve/coerce.mjs +0 -900
  116. package/dist/core/resolve/config.d.mts +0 -10
  117. package/dist/core/resolve/config.mjs +0 -19
  118. package/dist/core/resolve/contracts.d.mts +0 -146
  119. package/dist/core/resolve/errors.d.mts +0 -10
  120. package/dist/core/resolve/errors.mjs +0 -148
  121. package/dist/core/resolve/flags.d.mts +0 -74
  122. package/dist/core/resolve/flags.mjs +0 -246
  123. package/dist/core/resolve/index.d.mts +0 -44
  124. package/dist/core/resolve/index.mjs +0 -123
  125. package/dist/core/resolve/path-checks.d.mts +0 -48
  126. package/dist/core/resolve/path-checks.mjs +0 -102
  127. package/dist/core/resolve/redaction.d.mts +0 -13
  128. package/dist/core/resolve/redaction.mjs +0 -14
  129. package/dist/core/resolve/stages.d.mts +0 -86
  130. package/dist/core/resolve/stages.mjs +0 -170
  131. package/dist/core/resolve/standard.d.mts +0 -26
  132. package/dist/core/resolve/standard.mjs +0 -212
  133. package/dist/core/schema/activity.d.mts +0 -189
  134. package/dist/core/schema/arg.d.mts +0 -1461
  135. package/dist/core/schema/arg.mjs +0 -1139
  136. package/dist/core/schema/brand.d.mts +0 -17
  137. package/dist/core/schema/cardinality.d.mts +0 -302
  138. package/dist/core/schema/cardinality.mjs +0 -514
  139. package/dist/core/schema/command.d.mts +0 -1132
  140. package/dist/core/schema/command.mjs +0 -999
  141. package/dist/core/schema/flag.d.mts +0 -1495
  142. package/dist/core/schema/flag.mjs +0 -1207
  143. package/dist/core/schema/index.d.mts +0 -15
  144. package/dist/core/schema/index.mjs +0 -10
  145. package/dist/core/schema/middleware.d.mts +0 -129
  146. package/dist/core/schema/middleware.mjs +0 -41
  147. package/dist/core/schema/number-constraints.d.mts +0 -96
  148. package/dist/core/schema/number-constraints.mjs +0 -60
  149. package/dist/core/schema/prompt.d.mts +0 -135
  150. package/dist/core/schema/provenance.d.mts +0 -99
  151. package/dist/core/schema/provenance.mjs +0 -28
  152. package/dist/core/schema/run.d.mts +0 -211
  153. package/dist/core/schema/source.d.mts +0 -180
  154. package/dist/core/schema/source.mjs +0 -206
  155. package/dist/core/schema/standard.d.mts +0 -100
  156. package/dist/core/schema/standard.mjs +0 -15
  157. package/dist/core/schema/stdin.d.mts +0 -97
  158. package/dist/core/schema/stdin.mjs +0 -91
  159. package/dist/core/schema/string-constraints.d.mts +0 -108
  160. package/dist/core/schema/string-constraints.mjs +0 -86
  161. package/dist/core/schema/value-parsers.d.mts +0 -150
  162. package/dist/core/schema/value-parsers.mjs +0 -160
  163. package/dist/core/schema/value.d.mts +0 -243
  164. package/dist/core/schema/value.mjs +0 -573
  165. package/dist/core/testkit/index.d.mts +0 -63
  166. package/dist/core/testkit/index.mjs +0 -102
  167. package/dist/runtime/adapter.mjs +0 -92
  168. package/dist/runtime/auto.d.mts +0 -25
  169. package/dist/runtime/auto.mjs +0 -45
  170. package/dist/runtime/deno.d.mts +0 -99
  171. package/dist/runtime/deno.mjs +0 -265
  172. package/dist/runtime/detect.d.mts +0 -86
  173. package/dist/runtime/detect.mjs +0 -45
  174. package/dist/runtime/index.d.mts +0 -6
  175. package/dist/runtime/node.d.mts +0 -71
  176. package/dist/runtime/node.mjs +0 -228
  177. package/dist/runtime/paths.d.mts +0 -31
  178. package/dist/runtime/paths.mjs +0 -48
  179. package/dist/strings.d.mts +0 -27
  180. package/dist/strings.mjs +0 -22
  181. package/examples/basic.ts +0 -37
  182. package/examples/flag-types.ts +0 -79
  183. package/examples/gh/package.json +0 -45
  184. package/examples/gh/src/commands/auth.ts +0 -66
  185. package/examples/gh/src/commands/issue.ts +0 -120
  186. package/examples/gh/src/commands/pr.ts +0 -125
  187. package/examples/gh/src/data/issues.yaml +0 -5
  188. package/examples/gh/src/data/issues.yaml.d.ts +0 -17
  189. package/examples/gh/src/data/pull-requests.yaml +0 -7
  190. package/examples/gh/src/data/pull-requests.yaml.d.ts +0 -18
  191. package/examples/gh/src/docs.ts +0 -11
  192. package/examples/gh/src/lib/auth.ts +0 -37
  193. package/examples/gh/src/lib/utils.ts +0 -17
  194. package/examples/gh/src/main.test.ts +0 -307
  195. package/examples/gh/src/main.ts +0 -46
  196. package/examples/help-config.ts +0 -43
  197. package/examples/interactive.ts +0 -67
  198. package/examples/json-mode.ts +0 -95
  199. package/examples/middleware.ts +0 -71
  200. package/examples/multi-command.ts +0 -66
  201. package/examples/output-extras.ts +0 -46
  202. package/examples/parser-control.ts +0 -40
  203. package/examples/pwsh-demo/README.md +0 -40
  204. package/examples/pwsh-demo/package.json +0 -41
  205. package/examples/pwsh-demo/pwsh-demo.cmd +0 -3
  206. package/examples/pwsh-demo/smoke-powershell.ps1 +0 -218
  207. package/examples/pwsh-demo/src/main.test.ts +0 -45
  208. package/examples/pwsh-demo/src/main.ts +0 -140
  209. package/examples/spinner-progress.ts +0 -49
  210. package/examples/standard-schema.ts +0 -45
  211. package/examples/testing.ts +0 -147
  212. package/examples/transport-launcher.ts +0 -85
@@ -1,1207 +0,0 @@
1
- import { CLIError } from "../errors/index.mjs";
2
- import { assertNumberConstraints } from "./number-constraints.mjs";
3
- import { assertStringConstraints } from "./string-constraints.mjs";
4
- import { bytesValue, customValue, dateValue, durationValue, flagAggregateStandard, flagValueSchema, numberValue, pathValue, standardValue, stringValue, urlValue, valueDefinitionFields } from "./value.mjs";
5
- import { DUPLICATE_KEYS, SPLIT_FORMATS, defaultViolationError, flagCardinality, indefiniteArticle, isCollection, normalizeSplitOptions, normalizeSplitPolicy, validateDefault } from "./cardinality.mjs";
6
- import { isStandardSchemaV1 } from "./standard.mjs";
7
- import { normalizeStdinBinding } from "./stdin.mjs";
8
- //#region src/core/schema/flag.ts
9
- /**
10
- * Flag schema builder with full type inference.
11
- *
12
- * Each factory (`flag.string()`, `flag.boolean()`, etc.) returns an immutable
13
- * {@linkcode FlagBuilder} whose generic parameter tracks the value type and presence
14
- * state. Chained modifiers (`.default()`, `.required()`, `.alias()`, …) return
15
- * new builders with updated type-level and runtime state.
16
- *
17
- * @module dreamcli/core/schema/flag
18
- */
19
- /** All flag kind discriminators as a runtime array. */
20
- const FLAG_KINDS = [
21
- "string",
22
- "number",
23
- "boolean",
24
- "enum",
25
- "array",
26
- "custom",
27
- "count",
28
- "keyValue"
29
- ];
30
- /**
31
- * Normalise an alias input into a full {@link FlagAlias} object.
32
- *
33
- * @param alias - Raw alias name or structured alias object.
34
- * @returns Normalised alias record.
35
- */
36
- function normalizeFlagAlias(alias) {
37
- if (typeof alias === "string") return {
38
- name: alias,
39
- hidden: false
40
- };
41
- return {
42
- name: alias.name,
43
- hidden: alias.hidden
44
- };
45
- }
46
- /**
47
- * Normalise alias input into immutable alias records.
48
- *
49
- * @param aliases - Alias input values.
50
- * @returns Normalised alias objects.
51
- */
52
- function normalizeFlagAliases(aliases) {
53
- return aliases.map(normalizeFlagAlias);
54
- }
55
- /**
56
- * List alias names for a flag schema.
57
- *
58
- * @param schema - Flag schema whose aliases should be listed.
59
- * @param options - Visibility and length filtering.
60
- * @returns Alias names in registration order.
61
- */
62
- function getFlagAliasNames(schema, options) {
63
- const includeHidden = options?.includeHidden ?? false;
64
- const kind = options?.kind ?? "all";
65
- return schema.aliases.filter((alias) => includeHidden || !alias.hidden).filter((alias) => {
66
- if (kind === "short") return alias.name.length === 1;
67
- if (kind === "long") return alias.name.length > 1;
68
- return true;
69
- }).map((alias) => alias.name);
70
- }
71
- /**
72
- * Effective negated spelling for a flag, or `undefined` when not negatable.
73
- *
74
- * The builder cannot know its flag name, so a default (`no-<name>`) is
75
- * synthesized here — everywhere the canonical name is known (parser, help,
76
- * completions, collision validation).
77
- *
78
- * @param name - Canonical flag name.
79
- * @param schema - Flag schema (read for {@link FlagNegation}).
80
- * @returns The negated spelling without the `--` prefix.
81
- */
82
- function getFlagNegatedName(name, schema) {
83
- if (schema.negation === void 0) return void 0;
84
- return schema.negation.alias ?? `no-${name}`;
85
- }
86
- /** Every runtime key carried by a normalized {@link FlagSchema}. */
87
- const NORMALIZED_FLAG_SCHEMA_KEYS = [
88
- "kind",
89
- "presence",
90
- "defaultValue",
91
- "aliases",
92
- "stdin",
93
- "envVar",
94
- "configPath",
95
- "description",
96
- "enumValues",
97
- "numberConstraints",
98
- "stringConstraints",
99
- "elementSchema",
100
- "separator",
101
- "split",
102
- "duplicateKeys",
103
- "unique",
104
- "pathChecks",
105
- "valueHint",
106
- "prompt",
107
- "parseFn",
108
- "standard",
109
- "aggregateStandard",
110
- "deprecated",
111
- "propagate",
112
- "negation",
113
- "duplicates"
114
- ];
115
- /**
116
- * Whether an element input already carries every normalized schema key.
117
- *
118
- * @param element - Element definition or schema.
119
- * @returns `true` when the value is already a built {@link FlagSchema}.
120
- */
121
- function isNormalizedFlagSchema(element) {
122
- return NORMALIZED_FLAG_SCHEMA_KEYS.every((key) => key in element);
123
- }
124
- /** Reject flag-level fields on a collection factory's element builder. */
125
- function assertEligibleFlagElementBuilder(schema) {
126
- if (COLLECTION_FLAG_KINDS.includes(schema.kind) || schema.kind === "count") throw new CLIError(`Flag element schema kind '${schema.kind}' is not supported`, {
127
- code: "INVALID_SCHEMA",
128
- details: {
129
- kind: schema.kind,
130
- field: "kind"
131
- },
132
- suggest: "Use a scalar value kind for the collection element"
133
- });
134
- const defaults = [
135
- ["presence", schema.kind === "boolean" ? "defaulted" : "optional"],
136
- ["defaultValue", schema.kind === "boolean" ? false : void 0],
137
- ["stdin", void 0],
138
- ["envVar", void 0],
139
- ["configPath", void 0],
140
- ["description", void 0],
141
- ["elementSchema", void 0],
142
- ["separator", void 0],
143
- ["split", void 0],
144
- ["duplicateKeys", "last"],
145
- ["unique", false],
146
- ["prompt", void 0],
147
- ["aggregateStandard", void 0],
148
- ["deprecated", void 0],
149
- ["propagate", false],
150
- ["negation", void 0],
151
- ["duplicates", "last"]
152
- ];
153
- for (const [field, allowed] of defaults) {
154
- if (schema[field] === allowed) continue;
155
- throw new CLIError(`Flag element schema field '${String(field)}' is not supported`, {
156
- code: "INVALID_SCHEMA",
157
- details: {
158
- kind: schema.kind,
159
- field
160
- },
161
- suggest: `Drop '${String(field)}' from the collection element`
162
- });
163
- }
164
- if (schema.aliases.length !== 0) throw new CLIError("Flag element schema field 'aliases' is not supported", {
165
- code: "INVALID_SCHEMA",
166
- details: {
167
- kind: schema.kind,
168
- field: "aliases"
169
- },
170
- suggest: "Drop 'aliases' from the collection element"
171
- });
172
- }
173
- /**
174
- * Normalise an array flag's element input into a built {@link FlagSchema}.
175
- *
176
- * An already-built schema is returned unchanged, so repeated normalization
177
- * preserves element identity.
178
- *
179
- * @param element - Element definition or schema.
180
- * @returns The element as a fully populated {@link FlagSchema}.
181
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when a field belongs to a
182
- * different {@link FlagKind}.
183
- */
184
- function normalizeFlagElementSchema(element) {
185
- if (isNormalizedFlagSchema(element)) {
186
- assertValidFlagDefinition(element.kind, element);
187
- return element;
188
- }
189
- const { kind, ...fields } = element;
190
- assertValidFlagDefinition(kind, fields);
191
- return buildFlagSchema(kind, normalizeFlagDefinitionFields(fields));
192
- }
193
- /**
194
- * Resolve a definition's nested `elementSchema` into a built {@link FlagSchema}.
195
- *
196
- * @param fields - Definition fields excluding the kind discriminator.
197
- * @returns The same fields with `elementSchema` normalized.
198
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when a nested element field
199
- * belongs to a different {@link FlagKind}.
200
- */
201
- function normalizeFlagDefinitionFields(fields) {
202
- const { elementSchema, ...rest } = fields;
203
- if (elementSchema === void 0) return rest;
204
- return {
205
- ...rest,
206
- elementSchema: normalizeFlagElementSchema(elementSchema)
207
- };
208
- }
209
- /** Flag kinds that can read from stdin: every scalar, plus the collections. */
210
- const STDIN_CAPABLE_FLAG_KINDS = [
211
- "string",
212
- "number",
213
- "boolean",
214
- "enum",
215
- "custom",
216
- "array",
217
- "keyValue"
218
- ];
219
- /** The collection kinds, which carry an element schema and split policies. */
220
- const COLLECTION_FLAG_KINDS = ["array", "keyValue"];
221
- /**
222
- * Fields that are only meaningful on some {@link FlagKind}s, mapped to them.
223
- */
224
- const KIND_SPECIFIC_FLAG_FIELDS = [
225
- ["enumValues", ["enum"]],
226
- ["numberConstraints", ["number"]],
227
- ["stringConstraints", ["string"]],
228
- ["pathChecks", ["string"]],
229
- ["elementSchema", COLLECTION_FLAG_KINDS],
230
- ["separator", COLLECTION_FLAG_KINDS],
231
- ["split", COLLECTION_FLAG_KINDS],
232
- ["aggregateStandard", COLLECTION_FLAG_KINDS],
233
- ["parseFn", ["custom"]],
234
- ["negation", ["boolean"]]
235
- ];
236
- /**
237
- * Reject a definition that carries a field belonging to another {@link FlagKind}.
238
- *
239
- * A field set to `undefined` counts as absent, `unique` counts as absent when
240
- * `false`, and `duplicateKeys` counts as absent when `'last'`, so re-feeding a
241
- * built {@link FlagSchema} back through {@link createFlagSchema} stays valid: a
242
- * built schema always carries those defaults, whatever its kind. The compile-time
243
- * `this` parameter on `.unique()` and `.duplicateKeys()` is what rejects
244
- * `.duplicateKeys('last')` on a scalar, since the runtime cannot tell that call
245
- * apart from a round-tripped default.
246
- *
247
- * @param kind - Declared kind of the definition.
248
- * @param fields - Definition fields excluding the kind discriminator.
249
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an unknown kind or a kind
250
- * mismatch.
251
- * @internal
252
- */
253
- function assertValidFlagDefinition(kind, fields) {
254
- assertKnownFlagKind(kind);
255
- for (const [field, requiredKinds] of KIND_SPECIFIC_FLAG_FIELDS) {
256
- if (requiredKinds.includes(kind)) continue;
257
- if (fields[field] === void 0) continue;
258
- throw invalidFlagFieldError(kind, field, requiredKinds);
259
- }
260
- if (kind !== "array" && fields.unique === true) throw invalidFlagFieldError(kind, "unique", ["array"]);
261
- if (kind !== "keyValue" && fields.duplicateKeys !== void 0 && fields.duplicateKeys !== "last") throw invalidFlagFieldError(kind, "duplicateKeys", ["keyValue"]);
262
- if (fields.duplicateKeys !== void 0 && !DUPLICATE_KEYS.includes(fields.duplicateKeys)) throw new CLIError(`Unknown duplicate-key policy '${String(fields.duplicateKeys)}'`, {
263
- code: "INVALID_SCHEMA",
264
- details: {
265
- duplicateKeys: fields.duplicateKeys,
266
- allowed: [...DUPLICATE_KEYS]
267
- },
268
- suggest: `Use one of: ${DUPLICATE_KEYS.join(", ")}`
269
- });
270
- if (kind === "enum" && fields.enumValues === void 0) throw new CLIError("Flag schema kind 'enum' requires field 'enumValues'", {
271
- code: "INVALID_SCHEMA",
272
- details: {
273
- kind,
274
- field: "enumValues"
275
- },
276
- suggest: "Pass the allowed values in 'enumValues'"
277
- });
278
- if ((kind === "array" || kind === "count" || kind === "keyValue") && fields.duplicates !== void 0 && fields.duplicates !== "last") throw new CLIError(`Flag schema field 'duplicates' is not supported on kind '${kind}'`, {
279
- code: "INVALID_SCHEMA",
280
- details: {
281
- kind,
282
- field: "duplicates"
283
- },
284
- suggest: `Drop 'duplicates'; kind '${kind}' accumulates every occurrence`
285
- });
286
- if ((kind === "count" || kind === "keyValue") && fields.prompt !== void 0) throw new CLIError(`Flag schema field 'prompt' is not available on kind '${kind}'`, {
287
- code: "INVALID_SCHEMA",
288
- details: {
289
- kind,
290
- field: "prompt"
291
- },
292
- suggest: `Drop 'prompt' from the ${kind} flag`
293
- });
294
- if (fields.stdin !== void 0) assertStdinCapableKind(kind);
295
- }
296
- /**
297
- * Reject a discriminator outside {@link FLAG_KINDS}.
298
- *
299
- * The types admit only a declared kind, so this catches an untyped JavaScript
300
- * caller before an unknown discriminator reaches an exhaustive `switch` that
301
- * has no arm for it.
302
- *
303
- * @param kind - Declared kind of the definition.
304
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an unknown kind.
305
- * @internal
306
- */
307
- function assertKnownFlagKind(kind) {
308
- if (FLAG_KINDS.includes(kind)) return;
309
- throw new CLIError(`Unknown flag kind '${String(kind)}'`, {
310
- code: "INVALID_SCHEMA",
311
- details: {
312
- kind,
313
- allowed: [...FLAG_KINDS]
314
- },
315
- suggest: `Use one of: ${FLAG_KINDS.join(", ")}`
316
- });
317
- }
318
- /**
319
- * Reject a stdin binding on a flag kind that has no value to read.
320
- *
321
- * A `count` flag carries occurrences rather than a value, so both construction
322
- * paths refuse the binding with the same error.
323
- *
324
- * @param kind - Declared kind of the flag.
325
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a kind that cannot read stdin.
326
- */
327
- function assertStdinCapableKind(kind) {
328
- if (STDIN_CAPABLE_FLAG_KINDS.some((allowed) => allowed === kind)) return;
329
- throw new CLIError(`Flag schema field 'stdin' is not available on kind '${kind}'`, {
330
- code: "INVALID_SCHEMA",
331
- details: {
332
- kind,
333
- field: "stdin",
334
- allowedKinds: [...STDIN_CAPABLE_FLAG_KINDS]
335
- },
336
- suggest: `Drop 'stdin' or declare the flag as one of: ${STDIN_CAPABLE_FLAG_KINDS.join(", ")}`
337
- });
338
- }
339
- /**
340
- * Build the `'INVALID_SCHEMA'` error for a field used on the wrong kind.
341
- *
342
- * @param kind - Declared kind of the definition.
343
- * @param field - Offending field name.
344
- * @param requiredKind - Kind the field belongs to.
345
- * @returns The error to throw.
346
- */
347
- function invalidFlagFieldError(kind, field, requiredKinds) {
348
- const listed = requiredKinds.map((required) => `'${required}'`).join(" or ");
349
- return new CLIError(`Flag schema field '${field}' requires kind ${listed}, received kind '${kind}'`, {
350
- code: "INVALID_SCHEMA",
351
- details: {
352
- kind,
353
- field,
354
- requiredKinds: [...requiredKinds]
355
- },
356
- suggest: `Drop '${field}' or declare the flag as kind ${listed}`
357
- });
358
- }
359
- /**
360
- * Merge already-normalized schema fields onto the {@link FlagSchema} defaults.
361
- *
362
- * A field set to `undefined` falls back to its default for the fields
363
- * {@link FlagSchema} declares as non-nullable.
364
- *
365
- * @param kind - Discriminator for the value type this flag accepts.
366
- * @param overrides - Schema fields shallow-merged onto the defaults.
367
- * @returns A fully populated {@link FlagSchema}.
368
- */
369
- function buildFlagSchema(kind, overrides) {
370
- const schema = assembleFlagSchema(kind, overrides);
371
- assertValidFlagDefault(void 0, schema);
372
- return schema;
373
- }
374
- /** Merge the normalized fields onto the defaults, without validating the result. */
375
- function assembleFlagSchema(kind, overrides) {
376
- const aliases = overrides?.aliases !== void 0 ? normalizeFlagAliases(overrides.aliases) : [];
377
- const { aliases: _ignoredAliases, presence, stdin, unique, propagate, duplicates, duplicateKeys, ...rest } = overrides ?? {};
378
- return {
379
- kind,
380
- presence: presence ?? "optional",
381
- defaultValue: void 0,
382
- stdin: stdin === void 0 ? void 0 : normalizeStdinBinding(stdin),
383
- envVar: void 0,
384
- configPath: void 0,
385
- description: void 0,
386
- enumValues: void 0,
387
- numberConstraints: void 0,
388
- stringConstraints: void 0,
389
- elementSchema: void 0,
390
- separator: void 0,
391
- split: void 0,
392
- duplicateKeys: duplicateKeys ?? "last",
393
- unique: unique ?? false,
394
- pathChecks: void 0,
395
- valueHint: void 0,
396
- prompt: void 0,
397
- parseFn: void 0,
398
- standard: void 0,
399
- aggregateStandard: void 0,
400
- deprecated: void 0,
401
- propagate: propagate ?? false,
402
- negation: void 0,
403
- duplicates: duplicates ?? "last",
404
- ...rest,
405
- aliases
406
- };
407
- }
408
- /**
409
- * Reject a declared default the flag could never hold.
410
- *
411
- * A default is a typed value, so it is validated rather than decoded: string
412
- * and number constraints, element and aggregate Standard Schema verdicts
413
- * available synchronously, and the shape the cardinality requires. Filesystem
414
- * checks and asynchronous validators stay with the resolution-time pass.
415
- *
416
- * @param name - Canonical flag name, when one is known.
417
- * @param schema - The flag schema carrying the default.
418
- * @throws {CLIError} With code `'INVALID_DEFAULT'` when the default is invalid.
419
- */
420
- function assertValidFlagDefault(name, schema) {
421
- if (schema.defaultValue === void 0) return;
422
- const violation = validateDefault(flagValueSchema(schema), flagCardinality(schema), flagAggregateStandard(schema), schema.defaultValue);
423
- if (violation === void 0) return;
424
- throw defaultViolationError(name === void 0 ? `${indefiniteArticle(schema.kind)} ${schema.kind} flag` : `flag --${name}`, {
425
- kind: schema.kind,
426
- ...name === void 0 ? {} : { flag: name }
427
- }, violation);
428
- }
429
- function createFlagSchema(kindOrDefinition, overrides) {
430
- if (typeof kindOrDefinition === "string") {
431
- const fields = overrides ?? {};
432
- assertValidFlagDefinition(kindOrDefinition, fields);
433
- return buildFlagSchema(kindOrDefinition, normalizeFlagDefinitionFields(fields));
434
- }
435
- const { kind, ...fields } = kindOrDefinition;
436
- assertValidFlagDefinition(kind, fields);
437
- return buildFlagSchema(kind, normalizeFlagDefinitionFields(fields));
438
- }
439
- /**
440
- * Immutable flag schema builder.
441
- *
442
- * The type parameter `C` is a phantom that tracks the value type and presence
443
- * through the fluent chain. Each modifier returns a **new** builder — the
444
- * original is never mutated.
445
- *
446
- * @example
447
- * ```ts
448
- * const port = flag.number().default(8080);
449
- * type Port = InferFlag<typeof port>; // number
450
- *
451
- * const region = flag.enum(['us', 'eu', 'ap']);
452
- * type Region = InferFlag<typeof region>; // 'us' | 'eu' | 'ap' | undefined
453
- * ```
454
- */
455
- var FlagBuilder = class FlagBuilder {
456
- /** @internal Runtime schema descriptor. */
457
- schema;
458
- /**
459
- * Create a flag builder from a pre-built schema descriptor.
460
- *
461
- * @param schema - Runtime descriptor seeding this builder's state.
462
- */
463
- constructor(schema) {
464
- this.schema = schema;
465
- }
466
- /**
467
- * Provide a default value. The flag becomes "always present" — handlers
468
- * will never see `undefined`.
469
- *
470
- * The generic constraint `V extends C['valueType']` ensures the default
471
- * matches the flag's declared type.
472
- *
473
- * @param value - Fallback value used when no source provides one.
474
- * @returns The builder (for chaining).
475
- *
476
- * @example
477
- * ```ts
478
- * flag.number().default(8080).describe('Port to listen on')
479
- *
480
- * // $ mycli serve → port = 8080
481
- * // $ mycli serve --port 443 → port = 443
482
- * ```
483
- */
484
- default(value) {
485
- const schema = {
486
- ...this.schema,
487
- presence: "defaulted",
488
- defaultValue: value
489
- };
490
- assertValidFlagDefault(void 0, schema);
491
- return new FlagBuilder(schema);
492
- }
493
- /**
494
- * Mark the flag as required. If not resolved from any source the framework
495
- * will emit a `ValidationError` before the action handler runs.
496
- *
497
- * @returns The builder (for chaining).
498
- *
499
- * @example
500
- * ```ts
501
- * flag.string().required().describe('Deploy target')
502
- *
503
- * // $ mycli deploy
504
- * // # → Error: Missing required flag --target
505
- * // $ mycli deploy --target staging
506
- * // # → target = 'staging'
507
- * ```
508
- */
509
- required() {
510
- return new FlagBuilder({
511
- ...this.schema,
512
- presence: "required"
513
- });
514
- }
515
- /**
516
- * Add a short or long alias (e.g. `'f'` for `--force`, `'verbose'` as an
517
- * alternative long name).
518
- *
519
- * @param name - Single-char short alias or alternative long name.
520
- * @param options - Optional alias metadata. Hidden aliases remain parseable
521
- * but are omitted from help, completions, and suggestions.
522
- * @returns The builder (for chaining).
523
- *
524
- * @example
525
- * ```ts
526
- * flag.boolean().alias('v').describe('Enable verbose output')
527
- *
528
- * // $ mycli build -v → verbose = true
529
- * // $ mycli build --verbose → verbose = true
530
- * ```
531
- */
532
- alias(name, options) {
533
- return new FlagBuilder({
534
- ...this.schema,
535
- aliases: [...this.schema.aliases, {
536
- name,
537
- hidden: options?.hidden ?? false
538
- }]
539
- });
540
- }
541
- /**
542
- * Bind to an environment variable (resolved in v0.2+).
543
- *
544
- * The env value is read after CLI and stdin, and before config, the prompt,
545
- * and the default: CLI → stdin → **env** → config → prompt → default.
546
- *
547
- * @param varName - Environment variable name (e.g. `'PORT'`).
548
- * @returns The builder (for chaining).
549
- *
550
- * @example
551
- * ```ts
552
- * flag.string().env('API_KEY').describe('Service API key')
553
- *
554
- * // $ API_KEY=sk-123 mycli request → apiKey = 'sk-123'
555
- * // $ mycli request --api-key sk-456 → apiKey = 'sk-456' (CLI wins)
556
- * ```
557
- */
558
- env(varName) {
559
- return new FlagBuilder({
560
- ...this.schema,
561
- envVar: varName
562
- });
563
- }
564
- /**
565
- * Let this flag read its value from piped stdin.
566
- *
567
- * An explicit `--<name> -` is CLI-sourced with bytes from stdin and keeps
568
- * CLI precedence. An absent flag takes the stdin fallback stage, which sits
569
- * between CLI and env, so a flag set in the environment still reads stdin
570
- * and stdin wins. The whole buffer becomes the value, byte for byte for a
571
- * string flag; every other kind drops the single line terminator a pipe
572
- * appends before decoding, and `{ trim: true }` drops it for a string flag
573
- * too.
574
- *
575
- * A collection reads the buffer as elements instead: `--tag -` splices what
576
- * stdin decodes into the position the `-` occupies, so
577
- * `--tag before --tag - --tag after` over `'a\nb\n'` resolves to
578
- * `['before', 'a', 'b', 'after']`. `.split({ stdin })` sets the decoding.
579
- * Each `-` stands for the whole source, so `--tag - --tag -` splices the
580
- * buffer twice. A `-` typed beside other occurrences with nothing piped fails
581
- * with `MISSING_STDIN`; occurrences of nothing but `-` fall through to the
582
- * later sources.
583
- *
584
- * A stdin-enabled flag cannot receive a literal `-` as its value, since the
585
- * token names the source.
586
- *
587
- * Available on every flag kind except `count`. One command may declare a
588
- * single exclusive stdin consumer; pass `{ consume: 'broadcast' }` on every
589
- * input that should share the buffer.
590
- *
591
- * @param options - When to read stdin, how to share it, and whether to trim.
592
- * @returns The builder (for chaining).
593
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a `count` flag.
594
- *
595
- * @example
596
- * ```ts
597
- * flag.string().stdin().describe('Message body')
598
- * // $ echo hi | mycli send → body = 'hi\n'
599
- * // $ mycli send --body - → body reads stdin
600
- * // $ mycli send --body hello → body = 'hello'
601
- *
602
- * flag.string().stdin({ when: 'dash' })
603
- * // only `--body -` reads stdin
604
- *
605
- * flag.path({ mustExist: true }).stdin({ trim: true })
606
- * // $ echo ./dist | mycli clean → path = './dist', checked on disk
607
- * ```
608
- */
609
- stdin(options) {
610
- assertStdinCapableKind(this.schema.kind);
611
- return new FlagBuilder({
612
- ...this.schema,
613
- stdin: normalizeStdinBinding(options)
614
- });
615
- }
616
- /**
617
- * Bind to a dotted config path (resolved in v0.2+).
618
- *
619
- * The config value is read after CLI, stdin, and env, and before the prompt
620
- * and the default: CLI → stdin → env → **config** → prompt → default.
621
- *
622
- * @param path - Dotted config key (e.g. `'deploy.region'`).
623
- * @returns The builder (for chaining).
624
- *
625
- * @example
626
- * ```ts
627
- * flag.string().config('deploy.region').default('us-east-1')
628
- * // Config file: { "deploy": { "region": "eu-west-1" } }
629
- * // $ mycli deploy
630
- * // # → region = 'eu-west-1' (from config)
631
- * // $ mycli deploy --region ap-south-1
632
- * // # → CLI flag wins
633
- * ```
634
- */
635
- config(path) {
636
- return new FlagBuilder({
637
- ...this.schema,
638
- configPath: path
639
- });
640
- }
641
- /**
642
- * Human-readable description shown in help output.
643
- *
644
- * @param description - Text displayed next to the flag in `--help`.
645
- * @returns The builder (for chaining).
646
- */
647
- describe(description) {
648
- return new FlagBuilder({
649
- ...this.schema,
650
- description
651
- });
652
- }
653
- /**
654
- * Attach interactive prompt configuration for v0.3+ resolution.
655
- *
656
- * When a flag value is not resolved from CLI, stdin, env, or config, the
657
- * prompt engine uses this config to interactively ask the user.
658
- * In non-interactive contexts (CI, piped stdin) prompts are skipped
659
- * and resolution falls through to default or required validation.
660
- *
661
- * @param config - {@link PromptConfig} describing the interactive prompt.
662
- * @returns The builder (for chaining).
663
- *
664
- * @example
665
- * ```ts
666
- * flag.string().prompt({ kind: 'input', message: 'Enter value:' })
667
- *
668
- * // $ mycli init → prompts "Enter value:" interactively
669
- * // $ mycli init --name foo → skips prompt, uses CLI value
670
- * ```
671
- */
672
- prompt(config) {
673
- return new FlagBuilder({
674
- ...this.schema,
675
- prompt: config
676
- });
677
- }
678
- /**
679
- * Mark this flag as deprecated.
680
- *
681
- * When used, a warning is emitted to stderr. Help text shows
682
- * `[deprecated]` or `[deprecated: <reason>]`.
683
- *
684
- * Does not change the flag's type-level config — it's metadata only.
685
- *
686
- * @param message - Optional migration reason/guidance.
687
- * @returns The builder (for chaining).
688
- *
689
- * @example
690
- * ```ts
691
- * flag.string().deprecated('Use --target instead')
692
- *
693
- * // $ mycli deploy --dest staging
694
- * // ⚠ --dest is deprecated: Use --target instead
695
- * ```
696
- */
697
- deprecated(message) {
698
- return new FlagBuilder({
699
- ...this.schema,
700
- deprecated: message ?? true
701
- });
702
- }
703
- /**
704
- * Mark this flag as propagated to subcommands.
705
- *
706
- * Propagated flags are automatically available to all descendant
707
- * commands in a nested command tree. A child command that defines
708
- * a flag with the same name shadows the propagated parent flag.
709
- *
710
- * Does not change the flag's type-level config — it's metadata only.
711
- *
712
- * @returns The builder (for chaining).
713
- *
714
- * @example
715
- * ```ts
716
- * flag.boolean().alias('v').propagate().describe('Enable verbose output')
717
- *
718
- * // $ mycli --verbose deploy staging
719
- * // # → verbose = true in deploy handler
720
- * // $ mycli deploy --verbose staging
721
- * // # → same, inherited from parent
722
- * ```
723
- */
724
- propagate() {
725
- return new FlagBuilder({
726
- ...this.schema,
727
- propagate: true
728
- });
729
- }
730
- /**
731
- * Require an integer value. Composes with other numeric constraints.
732
- *
733
- * @param value - Whether to require an integer.
734
- * @defaultValue `true`
735
- * @returns The builder (for chaining).
736
- *
737
- * @example
738
- * ```ts
739
- * flag.number().int() // rejects 3.7, accepts 3
740
- * flag.number({ int: true }).int(false) // re-allows non-integers
741
- * ```
742
- */
743
- int(value = true) {
744
- return nextFlag({
745
- ...this.schema,
746
- numberConstraints: {
747
- ...this.schema.numberConstraints,
748
- int: value
749
- }
750
- });
751
- }
752
- /**
753
- * Set an inclusive lower bound. Composes with other numeric constraints;
754
- * a later call overrides an earlier `min` (including one from the options
755
- * object).
756
- *
757
- * @param value - Inclusive minimum.
758
- * @returns The builder (for chaining).
759
- *
760
- * @example
761
- * ```ts
762
- * flag.number().min(0) // rejects -1, accepts 0
763
- * flag.number({ min: 0 }).min(5) // effective min is 5
764
- * ```
765
- */
766
- min(value) {
767
- const numberConstraints = {
768
- ...this.schema.numberConstraints,
769
- min: value
770
- };
771
- assertNumberConstraints(numberConstraints);
772
- return nextFlag({
773
- ...this.schema,
774
- numberConstraints
775
- });
776
- }
777
- /**
778
- * Set an inclusive upper bound. Composes with other numeric constraints;
779
- * a later call overrides an earlier `max`.
780
- *
781
- * @param value - Inclusive maximum.
782
- * @returns The builder (for chaining).
783
- *
784
- * @example
785
- * ```ts
786
- * flag.number().max(100) // rejects 101, accepts 100
787
- * ```
788
- */
789
- max(value) {
790
- const numberConstraints = {
791
- ...this.schema.numberConstraints,
792
- max: value
793
- };
794
- assertNumberConstraints(numberConstraints);
795
- return nextFlag({
796
- ...this.schema,
797
- numberConstraints
798
- });
799
- }
800
- /**
801
- * Require (or, with `false`, allow) a finite value. Finiteness is enforced
802
- * by default, so this is mainly used as `.finite(false)` to re-allow
803
- * `Infinity` / `-Infinity`.
804
- *
805
- * @param allow - Whether to require a finite value.
806
- * @defaultValue `true`
807
- * @returns The builder (for chaining).
808
- *
809
- * @example
810
- * ```ts
811
- * flag.number().finite(false) // accepts Infinity
812
- * ```
813
- */
814
- finite(allow = true) {
815
- return nextFlag({
816
- ...this.schema,
817
- numberConstraints: {
818
- ...this.schema.numberConstraints,
819
- finite: allow
820
- }
821
- });
822
- }
823
- /**
824
- * Reject empty strings. Composes with other string constraints.
825
- *
826
- * @param value - Whether to reject empty strings.
827
- * @defaultValue `true`
828
- * @returns The builder (for chaining).
829
- *
830
- * @example
831
- * ```ts
832
- * flag.string().nonEmpty() // rejects '', accepts 'x'
833
- * ```
834
- */
835
- nonEmpty(value = true) {
836
- return nextFlag({
837
- ...this.schema,
838
- stringConstraints: {
839
- ...this.schema.stringConstraints,
840
- nonEmpty: value
841
- }
842
- });
843
- }
844
- /**
845
- * Set an inclusive minimum length (UTF-16 code units). Composes with other
846
- * string constraints; a later call overrides an earlier `minLength`.
847
- *
848
- * @param value - Inclusive minimum length.
849
- * @returns The builder (for chaining).
850
- *
851
- * @example
852
- * ```ts
853
- * flag.string().minLength(3) // rejects 'ab', accepts 'abc'
854
- * ```
855
- */
856
- minLength(value) {
857
- const stringConstraints = {
858
- ...this.schema.stringConstraints,
859
- minLength: value
860
- };
861
- assertStringConstraints(stringConstraints);
862
- return nextFlag({
863
- ...this.schema,
864
- stringConstraints
865
- });
866
- }
867
- /**
868
- * Set an inclusive maximum length (UTF-16 code units). Composes with other
869
- * string constraints; a later call overrides an earlier `maxLength`.
870
- *
871
- * @param value - Inclusive maximum length.
872
- * @returns The builder (for chaining).
873
- *
874
- * @example
875
- * ```ts
876
- * flag.string().maxLength(8) // rejects 9+ chars
877
- * ```
878
- */
879
- maxLength(value) {
880
- const stringConstraints = {
881
- ...this.schema.stringConstraints,
882
- maxLength: value
883
- };
884
- assertStringConstraints(stringConstraints);
885
- return nextFlag({
886
- ...this.schema,
887
- stringConstraints
888
- });
889
- }
890
- /**
891
- * Require the value to match a regular expression. Anchor with `^`/`$`
892
- * for full-string matching. Composes with other string constraints.
893
- *
894
- * @param value - Pattern the value must match.
895
- * @returns The builder (for chaining).
896
- *
897
- * @example
898
- * ```ts
899
- * flag.string().pattern(/^ghp_/) // rejects 'abc', accepts 'ghp_x'
900
- * ```
901
- */
902
- pattern(value) {
903
- return nextFlag({
904
- ...this.schema,
905
- stringConstraints: {
906
- ...this.schema.stringConstraints,
907
- pattern: value
908
- }
909
- });
910
- }
911
- /**
912
- * Split each CLI occurrence on a separator before element coercion, so
913
- * `--tag a,b --tag c` resolves to `['a', 'b', 'c']`. Elements are coerced
914
- * (and rejected) individually with the element schema's own error format.
915
- *
916
- * The separator is the CLI policy alone. Env values split on `','` and the
917
- * stdin buffer on line terminators unless `.split()` says otherwise.
918
- *
919
- * @param value - Separator string (e.g. `','`).
920
- * @returns The builder (for chaining).
921
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a flag that carries a
922
- * single value.
923
- *
924
- * @example
925
- * ```ts
926
- * flag.array(flag.enum(['us', 'eu', 'ap'])).separator(',')
927
- * // --region us,eu --region ap → ['us', 'eu', 'ap']
928
- * ```
929
- */
930
- separator(value) {
931
- normalizeSplitPolicy("cli", value);
932
- return nextFlag({
933
- ...this.schema,
934
- separator: value
935
- });
936
- }
937
- /**
938
- * Set how each source decodes into elements.
939
- *
940
- * CLI tokens accept `'whole'` and a delimiter; env values also accept
941
- * `'json'`; the stdin buffer accepts every format, including `'lines'`. The
942
- * strings `'whole'`, `'lines'`, and `'json'` name their format, and every
943
- * other string is the delimiter to split on. A source left out keeps what it
944
- * already had, or its default: whole CLI tokens (or the `.separator()`
945
- * delimiter), comma-delimited env values, line-delimited stdin. A config
946
- * value is a native array or object, and a config string decodes under the
947
- * env policy. For stdin, `'whole'` passes the complete buffer to a string
948
- * element, including its final line terminator.
949
- *
950
- * @param options - Per-source split settings.
951
- * @returns The builder (for chaining).
952
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a format the source does
953
- * not accept, an empty delimiter, or a flag that carries a single value.
954
- *
955
- * @example
956
- * ```ts
957
- * flag.array(flag.string()).split({ cli: ',', env: { format: 'json' } }).env('TAGS')
958
- * // --tag a,b → ['a', 'b']
959
- * // TAGS='["a","b"]' → ['a', 'b']
960
- * ```
961
- */
962
- split(options) {
963
- const normalized = normalizeSplitOptions(options, this.schema.split);
964
- return nextFlag({
965
- ...this.schema,
966
- ...normalized.setsSeparator ? { separator: normalized.separator } : {},
967
- split: normalized.split
968
- });
969
- }
970
- /**
971
- * Set how a repeated key combines.
972
- *
973
- * Applies to repeated CLI occurrences, delimited env pairs, and spliced stdin
974
- * reads in the same occurrence order. JSON decoding does not preserve
975
- * repeated object member names, so it cannot reliably expose them here.
976
- *
977
- * @param policy - `'last'` (default), `'first'`, or `'error'`.
978
- * @returns The builder (for chaining).
979
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a flag that is not
980
- * `keyValue`.
981
- *
982
- * @example
983
- * ```ts
984
- * flag.keyValue().duplicateKeys('error').env('VARS')
985
- * // $ VARS='A=1,A=2' mycli run
986
- * // # → Duplicate key '<redacted>' from env VARS for flag --env (CONSTRAINT_VIOLATED)
987
- * ```
988
- */
989
- duplicateKeys(policy) {
990
- return nextFlag({
991
- ...this.schema,
992
- duplicateKeys: policy
993
- });
994
- }
995
- /**
996
- * Validate the resolved value with a Standard Schema v1 validator.
997
- *
998
- * On a scalar builder the validator sees each value; on a collection builder
999
- * it sees the completed array or record, after every element passed its own
1000
- * validator. `flag.array(flag.string().standard(s))` validates elements,
1001
- * `flag.array(flag.string()).standard(s)` validates the array.
1002
- *
1003
- * @param schema - A Standard Schema v1 validator.
1004
- * @returns The builder (for chaining).
1005
- *
1006
- * @example
1007
- * ```ts
1008
- * import { z } from 'zod';
1009
- * flag.array(flag.string()).standard(z.array(z.string()).min(1))
1010
- * ```
1011
- */
1012
- standard(schema) {
1013
- const aggregate = isCollection(flagCardinality(this.schema));
1014
- return nextFlag({
1015
- ...this.schema,
1016
- ...aggregate ? { aggregateStandard: schema } : { standard: schema }
1017
- });
1018
- }
1019
- /**
1020
- * Deduplicate the resolved array, preserving first-seen order. Applied
1021
- * after all sources resolve, using `SameValueZero` semantics (like `Set`).
1022
- *
1023
- * @param value - Whether to deduplicate.
1024
- * @defaultValue `true`
1025
- * @returns The builder (for chaining).
1026
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a flag that is not
1027
- * `array`.
1028
- *
1029
- * @example
1030
- * ```ts
1031
- * flag.array(flag.string()).separator(',').unique()
1032
- * // --tag a,a --tag a → ['a']
1033
- * ```
1034
- */
1035
- unique(value = true) {
1036
- return nextFlag({
1037
- ...this.schema,
1038
- unique: value
1039
- });
1040
- }
1041
- /**
1042
- * Accept a negated spelling (`--no-<name>`) that sets the flag to `false`.
1043
- *
1044
- * Both spellings are ONE logical flag: the last CLI occurrence wins across
1045
- * them, and they share the duplicate policy. The negated spelling is
1046
- * presence-only — `--no-<name>=true` is rejected. Help renders the flag as
1047
- * `--[no-]<name>` (or lists a custom alias); env/config/prompt/default
1048
- * resolution is unaffected.
1049
- *
1050
- * @param options - Optional custom spelling (`alias`, without `--`) and
1051
- * `hidden` to keep the negated spelling parseable but unadvertised.
1052
- * @returns The builder (for chaining).
1053
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a flag that is not
1054
- * `boolean`.
1055
- *
1056
- * @example
1057
- * ```ts
1058
- * flag.boolean().default(true).negatable()
1059
- * // $ mycli build --no-sandbox → sandbox = false
1060
- * // $ mycli build --sandbox → sandbox = true
1061
- * ```
1062
- */
1063
- negatable(options) {
1064
- return nextFlag({
1065
- ...this.schema,
1066
- negation: {
1067
- alias: options?.alias,
1068
- hidden: options?.hidden ?? false
1069
- }
1070
- });
1071
- }
1072
- /**
1073
- * Set how repeated CLI occurrences of this flag combine.
1074
- *
1075
- * Counted per logical flag — aliases and the negated spelling all count
1076
- * toward the same flag. CLI tokens only: env/config/prompt/default
1077
- * resolution keeps its precedence semantics. Not available on `array`,
1078
- * `count`, or `keyValue` flags, which inherently accumulate.
1079
- *
1080
- * @param policy - `'last'` (default), `'first'`, or `'error'`.
1081
- * @returns The builder (for chaining).
1082
- *
1083
- * @example
1084
- * ```ts
1085
- * flag.enum(['session', 'same-dir', 'worktree']).duplicates('error')
1086
- * // $ mycli run --spawn session --spawn worktree
1087
- * // # → Error: Flag --spawn may only be specified once
1088
- * ```
1089
- */
1090
- duplicates(policy) {
1091
- return nextFlag({
1092
- ...this.schema,
1093
- duplicates: policy
1094
- });
1095
- }
1096
- };
1097
- /**
1098
- * Continue a builder chain, rejecting a schema the change just invalidated.
1099
- *
1100
- * The `this` constraint on each modifier states to the compiler which kinds
1101
- * carry the field it sets; this states the same rule to a caller who reaches
1102
- * the builder from JavaScript, with the error {@link createFlagSchema} already
1103
- * gives, so what a builder produces is always a definition the framework can
1104
- * read back.
1105
- *
1106
- * A constraint added after `.default()` still governs the default, so the
1107
- * verdict is the same whichever order the chain was written in.
1108
- *
1109
- * @param schema - The schema the modifier produced.
1110
- * @returns A builder over that schema.
1111
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when the field does not belong
1112
- * on the flag, or `'INVALID_DEFAULT'` when the default no longer holds.
1113
- * @internal
1114
- */
1115
- function nextFlag(schema) {
1116
- assertValidFlagDefinition(schema.kind, schema);
1117
- assertValidFlagDefault(void 0, schema);
1118
- return new FlagBuilder(schema);
1119
- }
1120
- /**
1121
- * Flag schema factory. Call `flag.<kind>()` to create an immutable
1122
- * {@link FlagBuilder} with full type inference and safe modifier chaining.
1123
- */
1124
- const flag = {
1125
- string(constraints) {
1126
- if (constraints !== void 0) assertStringConstraints(constraints);
1127
- return new FlagBuilder(createFlagSchema("string", valueDefinitionFields(stringValue(constraints))));
1128
- },
1129
- number(constraints) {
1130
- if (constraints !== void 0) assertNumberConstraints(constraints);
1131
- return new FlagBuilder(createFlagSchema("number", valueDefinitionFields(numberValue(constraints))));
1132
- },
1133
- boolean() {
1134
- return new FlagBuilder(createFlagSchema("boolean", {
1135
- presence: "defaulted",
1136
- defaultValue: false
1137
- }));
1138
- },
1139
- enum(values) {
1140
- return new FlagBuilder(createFlagSchema("enum", { enumValues: values }));
1141
- },
1142
- array(element) {
1143
- assertFlagElementBuilder("array", element);
1144
- return new FlagBuilder(createFlagSchema("array", { elementSchema: element.schema }));
1145
- },
1146
- custom(parseFnOrSchema) {
1147
- if (isStandardSchemaV1(parseFnOrSchema)) return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(standardValue(parseFnOrSchema))));
1148
- return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(customValue(parseFnOrSchema))));
1149
- },
1150
- url(options) {
1151
- return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(urlValue(options))));
1152
- },
1153
- path(options) {
1154
- return new FlagBuilder(createFlagSchema("string", valueDefinitionFields(pathValue(options))));
1155
- },
1156
- date(options) {
1157
- return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(dateValue(options))));
1158
- },
1159
- duration() {
1160
- return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(durationValue())));
1161
- },
1162
- bytes() {
1163
- return new FlagBuilder(createFlagSchema("custom", valueDefinitionFields(bytesValue())));
1164
- },
1165
- count() {
1166
- return new FlagBuilder(createFlagSchema("count", {
1167
- presence: "defaulted",
1168
- defaultValue: 0
1169
- }));
1170
- },
1171
- keyValue(element) {
1172
- if (element !== void 0) assertFlagElementBuilder("keyValue", element);
1173
- return new FlagBuilder(createFlagSchema("keyValue", {
1174
- valueHint: "key=value",
1175
- ...element !== void 0 ? { elementSchema: element.schema } : {}
1176
- }));
1177
- }
1178
- };
1179
- /**
1180
- * Reject a collection factory handed something other than a flag builder.
1181
- *
1182
- * The types demand one, so this catches an untyped JavaScript caller before the
1183
- * factory reads `.schema` off a value that has none.
1184
- *
1185
- * @param factory - Name of the factory being called.
1186
- * @param element - What the caller passed as the element.
1187
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when it is not a
1188
- * {@link FlagBuilder}.
1189
- * @internal
1190
- */
1191
- function assertFlagElementBuilder(factory, element) {
1192
- if (element instanceof FlagBuilder) {
1193
- assertEligibleFlagElementBuilder(element.schema);
1194
- return;
1195
- }
1196
- throw new CLIError(`flag.${factory}() requires an element builder`, {
1197
- code: "INVALID_SCHEMA",
1198
- details: {
1199
- factory,
1200
- field: "element",
1201
- received: typeof element
1202
- },
1203
- suggest: `Pass an element builder, as in flag.${factory}(flag.string())`
1204
- });
1205
- }
1206
- //#endregion
1207
- export { DUPLICATE_KEYS, FLAG_KINDS, FlagBuilder, SPLIT_FORMATS, createFlagSchema, flag, getFlagAliasNames, getFlagNegatedName, normalizeFlagAlias, normalizeFlagAliases };