@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,1139 +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 { argAggregateStandard, argValueSchema, booleanValue, bytesValue, dateValue, durationValue, numberValue, pathValue, standardValue, stringParsedValue, stringValue, urlValue, valueDefinitionFields } from "./value.mjs";
5
- import { DUPLICATE_KEYS, argCardinality, defaultViolationError, 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/arg.ts
9
- /**
10
- * Positional argument schema builder with full type inference.
11
- *
12
- * Each factory (`arg.string()`, `arg.number()`, `arg.enum()`, `arg.custom()`,
13
- * `arg.url()`, `arg.path()`, `arg.date()`, `arg.duration()`, `arg.bytes()`)
14
- * returns an immutable {@linkcode ArgBuilder} whose generic parameter tracks the
15
- * value type, presence state, and variadic flag through the fluent chain.
16
- *
17
- * @module dreamcli/core/schema/arg
18
- */
19
- /** All arg kind discriminators as a runtime array. */
20
- const ARG_KINDS = [
21
- "string",
22
- "number",
23
- "boolean",
24
- "enum",
25
- "custom",
26
- "keyValue"
27
- ];
28
- /** Fields only an arg that aggregates can carry. */
29
- const COLLECTION_ARG_FIELDS = ["separator", "split"];
30
- /**
31
- * Fields that are only meaningful on one {@link ArgKind}, mapped to that kind.
32
- */
33
- const KIND_SPECIFIC_ARG_FIELDS = [
34
- ["enumValues", "enum"],
35
- ["numberConstraints", "number"],
36
- ["stringConstraints", "string"],
37
- ["pathChecks", "string"],
38
- ["parseFn", "custom"],
39
- ["duplicateKeys", "keyValue"],
40
- ["elementSchema", "keyValue"]
41
- ];
42
- /** Every runtime key carried by a normalized {@link ArgSchema}. */
43
- const NORMALIZED_ARG_SCHEMA_KEYS = [
44
- "kind",
45
- "presence",
46
- "variadic",
47
- "stdin",
48
- "defaultValue",
49
- "description",
50
- "envVar",
51
- "configPath",
52
- "prompt",
53
- "enumValues",
54
- "elementSchema",
55
- "numberConstraints",
56
- "stringConstraints",
57
- "pathChecks",
58
- "valueHint",
59
- "parseFn",
60
- "separator",
61
- "split",
62
- "duplicateKeys",
63
- "unique",
64
- "standard",
65
- "aggregateStandard",
66
- "deprecated"
67
- ];
68
- /**
69
- * Whether an element input already carries every normalized schema key.
70
- *
71
- * @param element - Element definition or schema.
72
- * @returns `true` when the value is already a built {@link ArgSchema}.
73
- */
74
- function isNormalizedArgSchema(element) {
75
- return NORMALIZED_ARG_SCHEMA_KEYS.every((key) => Object.hasOwn(element, key));
76
- }
77
- /**
78
- * Reject positional-only fields on a key-value entry's value schema.
79
- *
80
- * Entry values use only their codec, constraints, validator, path checks, and
81
- * value hint. Sources, presence, collection settings, metadata, and another
82
- * key-value layer would otherwise be accepted and silently ignored.
83
- *
84
- * @param schema - Normalized schema proposed as an entry value.
85
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an unsupported shape.
86
- * @internal
87
- */
88
- function assertValidArgElementSchema(schema) {
89
- if (schema.kind === "keyValue") throw new CLIError("Arg element schema kind 'keyValue' is not supported", {
90
- code: "INVALID_SCHEMA",
91
- details: {
92
- kind: schema.kind,
93
- field: "kind"
94
- },
95
- suggest: "Use a scalar value kind for the key-value element"
96
- });
97
- for (const [field, allowed] of [
98
- ["presence", "required"],
99
- ["variadic", false],
100
- ["stdin", void 0],
101
- ["defaultValue", void 0],
102
- ["description", void 0],
103
- ["envVar", void 0],
104
- ["configPath", void 0],
105
- ["prompt", void 0],
106
- ["elementSchema", void 0],
107
- ["separator", void 0],
108
- ["split", void 0],
109
- ["duplicateKeys", "last"],
110
- ["unique", false],
111
- ["aggregateStandard", void 0],
112
- ["deprecated", void 0]
113
- ]) {
114
- if (schema[field] === allowed) continue;
115
- throw new CLIError(`Arg element schema field '${String(field)}' is not supported`, {
116
- code: "INVALID_SCHEMA",
117
- details: {
118
- kind: schema.kind,
119
- field
120
- },
121
- suggest: `Drop '${String(field)}' from the key-value element`
122
- });
123
- }
124
- }
125
- /**
126
- * Normalize an entries arg's element input into a built {@link ArgSchema}.
127
- *
128
- * An already-built schema is returned unchanged, so repeated normalization
129
- * preserves element identity.
130
- *
131
- * @param element - Element definition or schema.
132
- * @returns The element as a fully populated {@link ArgSchema}.
133
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when a nested element field
134
- * belongs to a different {@link ArgKind}.
135
- */
136
- function normalizeArgElementSchema(element) {
137
- if (isNormalizedArgSchema(element)) {
138
- assertValidArgDefinition(element.kind, element);
139
- assertValidArgElementSchema(element);
140
- return element;
141
- }
142
- const { kind, ...fields } = element;
143
- assertValidArgDefinition(kind, fields);
144
- const schema = buildArgSchema(kind, normalizeArgDefinitionFields(fields));
145
- assertValidArgElementSchema(schema);
146
- return schema;
147
- }
148
- /**
149
- * Resolve a definition's nested `elementSchema` into a built {@link ArgSchema}.
150
- *
151
- * @param fields - Definition fields excluding the kind discriminator.
152
- * @returns The same fields with `elementSchema` normalized.
153
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when a nested element field
154
- * belongs to a different {@link ArgKind}.
155
- */
156
- function normalizeArgDefinitionFields(fields) {
157
- const { elementSchema, ...rest } = fields;
158
- if (elementSchema === void 0) return rest;
159
- return {
160
- ...rest,
161
- elementSchema: normalizeArgElementSchema(elementSchema)
162
- };
163
- }
164
- /**
165
- * Reject a definition that carries a field belonging to another {@link ArgKind}.
166
- *
167
- * A field set to `undefined` counts as absent, and `duplicateKeys` counts as
168
- * absent when `'last'`, so re-feeding a built {@link ArgSchema} back through
169
- * {@link createArgSchema} stays valid: a built schema always carries that
170
- * default, whatever its kind. The compile-time `this` parameter on
171
- * `.duplicateKeys()` is what rejects `.duplicateKeys('last')` on a scalar, since
172
- * the runtime cannot tell that call apart from a round-tripped default.
173
- *
174
- * @param kind - Declared kind of the definition.
175
- * @param fields - Definition fields excluding the kind discriminator.
176
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an unknown kind or a kind
177
- * mismatch.
178
- */
179
- function assertValidArgDefinition(kind, fields) {
180
- assertKnownArgKind(kind);
181
- for (const [field, requiredKind] of KIND_SPECIFIC_ARG_FIELDS) {
182
- if (kind === requiredKind) continue;
183
- if (fields[field] === void 0) continue;
184
- if (field === "duplicateKeys" && fields[field] === "last") continue;
185
- throw new CLIError(`Arg schema field '${field}' requires kind '${requiredKind}', received kind '${kind}'`, {
186
- code: "INVALID_SCHEMA",
187
- details: {
188
- kind,
189
- field,
190
- requiredKind
191
- },
192
- suggest: `Drop '${field}' or declare the arg as kind '${requiredKind}'`
193
- });
194
- }
195
- if (kind === "enum" && fields.enumValues === void 0) throw new CLIError("Arg schema kind 'enum' requires field 'enumValues'", {
196
- code: "INVALID_SCHEMA",
197
- details: {
198
- kind,
199
- field: "enumValues"
200
- },
201
- suggest: "Pass the allowed values in 'enumValues'"
202
- });
203
- if (fields.duplicateKeys !== void 0 && !DUPLICATE_KEYS.includes(fields.duplicateKeys)) throw new CLIError(`Unknown duplicate-key policy '${String(fields.duplicateKeys)}'`, {
204
- code: "INVALID_SCHEMA",
205
- details: {
206
- duplicateKeys: fields.duplicateKeys,
207
- allowed: [...DUPLICATE_KEYS]
208
- },
209
- suggest: `Use one of: ${DUPLICATE_KEYS.join(", ")}`
210
- });
211
- const aggregates = kind === "keyValue" || fields.variadic === true;
212
- if (fields.aggregateStandard !== void 0 && !aggregates) throw new CLIError(`Arg schema field 'aggregateStandard' requires a collection, received a non-variadic '${kind}' arg`, {
213
- code: "INVALID_SCHEMA",
214
- details: {
215
- kind,
216
- field: "aggregateStandard"
217
- },
218
- suggest: "Add 'variadic: true', declare the arg as kind 'keyValue', or use 'standard'"
219
- });
220
- if (kind === "keyValue" && fields.prompt !== void 0) throw new CLIError("Arg schema field 'prompt' is not available on kind 'keyValue'", {
221
- code: "INVALID_SCHEMA",
222
- details: {
223
- kind,
224
- field: "prompt"
225
- },
226
- suggest: "Drop 'prompt' from the keyValue argument"
227
- });
228
- for (const field of COLLECTION_ARG_FIELDS) {
229
- if (fields[field] === void 0 || aggregates) continue;
230
- throw new CLIError(`Arg schema field '${field}' requires a collection, received a non-variadic '${kind}' arg`, {
231
- code: "INVALID_SCHEMA",
232
- details: {
233
- kind,
234
- field
235
- },
236
- suggest: `Add 'variadic: true', declare the arg as kind 'keyValue', or drop '${field}'`
237
- });
238
- }
239
- if (fields.unique === true && (kind === "keyValue" || fields.variadic !== true)) throw new CLIError("Arg schema field 'unique' requires a variadic arg of a list kind", {
240
- code: "INVALID_SCHEMA",
241
- details: {
242
- kind,
243
- field: "unique"
244
- },
245
- suggest: "Add 'variadic: true' on a list kind, or drop 'unique'"
246
- });
247
- }
248
- /**
249
- * Reject a discriminator outside {@link ARG_KINDS}.
250
- *
251
- * The types admit only a declared kind, so this catches an untyped JavaScript
252
- * caller before an unknown discriminator reaches an exhaustive `switch` that
253
- * has no arm for it.
254
- *
255
- * @param kind - Declared kind of the definition.
256
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an unknown kind.
257
- */
258
- function assertKnownArgKind(kind) {
259
- if (ARG_KINDS.includes(kind)) return;
260
- throw new CLIError(`Unknown arg kind '${String(kind)}'`, {
261
- code: "INVALID_SCHEMA",
262
- details: {
263
- kind,
264
- allowed: [...ARG_KINDS]
265
- },
266
- suggest: `Use one of: ${ARG_KINDS.join(", ")}`
267
- });
268
- }
269
- /**
270
- * Merge definition fields onto the {@link ArgSchema} defaults.
271
- *
272
- * A field set to `undefined` falls back to its default for the fields
273
- * {@link ArgSchema} declares as non-nullable.
274
- *
275
- * @param kind - Discriminator for the value type this arg accepts.
276
- * @param overrides - Definition fields shallow-merged onto the defaults.
277
- * @returns A fully populated {@link ArgSchema}.
278
- */
279
- function buildArgSchema(kind, overrides) {
280
- const schema = assembleArgSchema(kind, overrides);
281
- assertValidArgDefault(void 0, schema);
282
- return schema;
283
- }
284
- /** Merge the definition fields onto the defaults, without validating the result. */
285
- function assembleArgSchema(kind, overrides) {
286
- const { presence, variadic, stdin, unique, duplicateKeys, ...rest } = overrides ?? {};
287
- return {
288
- kind,
289
- presence: presence ?? "required",
290
- variadic: variadic ?? false,
291
- stdin: stdin === void 0 ? void 0 : normalizeStdinBinding(stdin),
292
- defaultValue: void 0,
293
- description: void 0,
294
- envVar: void 0,
295
- configPath: void 0,
296
- prompt: void 0,
297
- enumValues: void 0,
298
- elementSchema: void 0,
299
- numberConstraints: void 0,
300
- stringConstraints: void 0,
301
- pathChecks: void 0,
302
- valueHint: void 0,
303
- parseFn: void 0,
304
- separator: void 0,
305
- split: void 0,
306
- duplicateKeys: duplicateKeys ?? "last",
307
- unique: unique ?? false,
308
- standard: void 0,
309
- aggregateStandard: void 0,
310
- deprecated: void 0,
311
- ...rest
312
- };
313
- }
314
- /**
315
- * Reject a declared default the arg could never hold.
316
- *
317
- * A default is a typed value, so it is validated rather than decoded: string
318
- * and number constraints, element and aggregate Standard Schema verdicts
319
- * available synchronously, and the shape the cardinality requires. Filesystem
320
- * checks and asynchronous validators stay with the resolution-time pass.
321
- *
322
- * @param name - Positional arg name, when one is known.
323
- * @param schema - The arg schema carrying the default.
324
- * @throws {CLIError} With code `'INVALID_DEFAULT'` when the default is invalid.
325
- */
326
- function assertValidArgDefault(name, schema) {
327
- if (schema.defaultValue === void 0) return;
328
- const violation = validateDefault(argValueSchema(schema), argCardinality(schema), argAggregateStandard(schema), schema.defaultValue);
329
- if (violation === void 0) return;
330
- throw defaultViolationError(name === void 0 ? `${indefiniteArticle(schema.kind)} ${schema.kind} argument` : `argument <${name}>`, {
331
- kind: schema.kind,
332
- ...name === void 0 ? {} : { arg: name }
333
- }, violation);
334
- }
335
- function createArgSchema(kindOrDefinition, overrides) {
336
- if (typeof kindOrDefinition === "string") {
337
- assertValidArgDefinition(kindOrDefinition, overrides ?? {});
338
- return buildArgSchema(kindOrDefinition, normalizeArgDefinitionFields(overrides ?? {}));
339
- }
340
- const { kind, ...fields } = kindOrDefinition;
341
- assertValidArgDefinition(kind, fields);
342
- return buildArgSchema(kind, normalizeArgDefinitionFields(fields));
343
- }
344
- /**
345
- * Immutable positional argument schema builder.
346
- *
347
- * The type parameter `C` is a phantom that tracks the value type, presence,
348
- * and variadic state through the fluent chain. Each modifier returns a **new**
349
- * builder — the original is never mutated.
350
- *
351
- * @example
352
- * ```ts
353
- * // Full command with multiple args and modifiers
354
- * import { command, arg } from '@kjanat/dreamcli';
355
- *
356
- * command('deploy')
357
- * .arg('target', arg.string()
358
- * .env('DEPLOY_TARGET')
359
- * .describe('Deploy target'))
360
- * .arg('port', arg.number()
361
- * .env('PORT')
362
- * .default(3000)
363
- * .describe('Port number'))
364
- * .arg('files', arg.string()
365
- * .variadic()
366
- * .optional()
367
- * .describe('Extra config files'))
368
- * .action(({ args }) => {
369
- * args.target; // string (required, from CLI or $DEPLOY_TARGET)
370
- * args.port; // number (defaulted, from CLI, $PORT, or 3000)
371
- * args.files; // string[] (optional variadic)
372
- * });
373
- * ```
374
- *
375
- * @example
376
- * ```ts
377
- * // Type inference
378
- * const target = arg.string();
379
- * type T = InferArg<typeof target>; // string
380
- *
381
- * const opt = arg.string().optional();
382
- * type O = InferArg<typeof opt>; // string | undefined
383
- *
384
- * const files = arg.string().variadic();
385
- * type F = InferArg<typeof files>; // string[]
386
- * ```
387
- */
388
- var ArgBuilder = class ArgBuilder {
389
- /** @internal Runtime schema descriptor. */
390
- schema;
391
- /**
392
- * Create an arg builder from a pre-built schema descriptor.
393
- *
394
- * @param schema - Runtime descriptor for this positional argument.
395
- */
396
- constructor(schema) {
397
- this.schema = schema;
398
- }
399
- /**
400
- * Mark the arg as required (this is the default for positional args).
401
- * Produces an error if no value resolves from any configured source
402
- * (CLI → stdin → env → config → prompt → default).
403
- *
404
- * @example
405
- * ```ts
406
- * arg.string().required() // explicit, same as default
407
- *
408
- * // In a command — omitting <target> causes a ValidationError:
409
- * command('deploy')
410
- * .arg('target', arg.string().required().describe('Deploy target'))
411
- * // $ mycli deploy
412
- * // Error: Missing required argument <target>
413
- * ```
414
- *
415
- * @returns The builder (for chaining).
416
- */
417
- required() {
418
- return new ArgBuilder({
419
- ...this.schema,
420
- presence: "required"
421
- });
422
- }
423
- /**
424
- * Mark the arg as optional. Handlers receive `undefined` when absent.
425
- *
426
- * @example
427
- * ```ts
428
- * arg.string().optional()
429
- *
430
- * // In a command — handler receives `undefined` when omitted:
431
- * command('greet')
432
- * .arg('name', arg.string().optional().describe('Who to greet'))
433
- * .action(({ args }) => {
434
- * args.name; // string | undefined
435
- * });
436
- * // $ mycli greet → args.name is undefined
437
- * // $ mycli greet Alice → args.name is 'Alice'
438
- * ```
439
- *
440
- * @returns The builder (for chaining).
441
- */
442
- optional() {
443
- return new ArgBuilder({
444
- ...this.schema,
445
- presence: "optional"
446
- });
447
- }
448
- /**
449
- * Provide a default value. The arg becomes "always present" — handlers
450
- * will never see `undefined`.
451
- *
452
- * The generic constraint {@link ArgDefaultValue} ensures the default matches
453
- * what the arg resolves to: an array for a variadic arg, a record for a
454
- * `keyValue` one, and a single value otherwise.
455
- *
456
- * Resolution order when extra sources are configured:
457
- * CLI → stdin → env → config → prompt → **default**.
458
- *
459
- * @param value - Fallback used when no CLI value or env var resolves.
460
- * @returns The builder (for chaining).
461
- * @throws {CLIError} With code `'INVALID_DEFAULT'` when the value is one the
462
- * arg could never hold.
463
- *
464
- * @example
465
- * ```ts
466
- * arg.string().default('production')
467
- * arg.number().default(3000)
468
- * arg.string().variadic().default(['a', 'b'])
469
- *
470
- * // In a command — default kicks in when CLI and env are both absent:
471
- * command('deploy')
472
- * .arg('env', arg.string()
473
- * .env('DEPLOY_ENV')
474
- * .default('staging')
475
- * .describe('Target environment'))
476
- * .action(({ args }) => {
477
- * args.env; // string (never undefined)
478
- * });
479
- * // $ mycli deploy → 'staging' (default)
480
- * // $ DEPLOY_ENV=prod mycli deploy → 'prod' (env)
481
- * // $ mycli deploy production → 'production' (CLI)
482
- * ```
483
- */
484
- default(value) {
485
- const schema = {
486
- ...this.schema,
487
- presence: "defaulted",
488
- defaultValue: value
489
- };
490
- assertValidArgDefault(void 0, schema);
491
- return new ArgBuilder(schema);
492
- }
493
- /**
494
- * Mark this arg as variadic — it consumes all remaining positional
495
- * arguments. The inferred type becomes `T[]`.
496
- *
497
- * A variadic arg is the last positional a command can declare. Registering
498
- * another positional after it throws `INVALID_BUILDER_STATE` from `.arg()`
499
- * and from `createCommandSchema()`.
500
- *
501
- * @example
502
- * ```ts
503
- * arg.string().variadic()
504
- *
505
- * // In a command — collects all remaining positionals:
506
- * command('build')
507
- * .arg('entry', arg.string().describe('Main entry'))
508
- * .arg('extras', arg.string().variadic().optional().describe('Extra files'))
509
- * .action(({ args }) => {
510
- * args.entry; // string
511
- * args.extras; // string[]
512
- * });
513
- * // $ mycli build main.ts a.ts b.ts
514
- * // → entry = 'main.ts', extras = ['a.ts', 'b.ts']
515
- * ```
516
- *
517
- * @returns The builder (for chaining).
518
- */
519
- variadic() {
520
- return nextArg({
521
- ...this.schema,
522
- variadic: true
523
- });
524
- }
525
- /**
526
- * Split each positional token on a separator before element coercion, so
527
- * `mycli build a,b c` collects `['a', 'b', 'c']` into a variadic arg.
528
- *
529
- * The separator is the CLI policy alone. Env values split on `','` and the
530
- * stdin buffer on line terminators unless `.split()` says otherwise.
531
- *
532
- * Available on an arg that aggregates, so call it after `.variadic()` or on
533
- * `arg.keyValue()`.
534
- *
535
- * @param value - Separator string (e.g. `','`).
536
- * @returns The builder (for chaining).
537
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an arg carrying a single
538
- * value.
539
- */
540
- separator(value) {
541
- normalizeSplitPolicy("cli", value);
542
- return nextArg({
543
- ...this.schema,
544
- separator: value
545
- });
546
- }
547
- /**
548
- * Set how each source decodes into elements.
549
- *
550
- * CLI tokens accept `'whole'` and a delimiter; env values also accept
551
- * `'json'`; the stdin buffer accepts every format, including `'lines'`. The
552
- * strings `'whole'`, `'lines'`, and `'json'` name their format, and every
553
- * other string is the delimiter to split on. A source left out keeps what it
554
- * already had, or its default: whole CLI tokens, comma-delimited env values,
555
- * line-delimited stdin. For stdin, `'whole'` passes the complete buffer to a
556
- * string element, including its final line terminator.
557
- *
558
- * Available on an arg that aggregates, so call it after `.variadic()` or on
559
- * `arg.keyValue()`.
560
- *
561
- * @param options - Per-source split settings.
562
- * @returns The builder (for chaining).
563
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on a format the source does
564
- * not accept, an empty delimiter, or an arg carrying a single value.
565
- *
566
- * @example
567
- * ```ts
568
- * arg.string().variadic().split({ env: { format: 'json' } })
569
- * // FILES='["a.ts","b.ts"]' → ['a.ts', 'b.ts']
570
- * ```
571
- */
572
- split(options) {
573
- const normalized = normalizeSplitOptions(options, this.schema.split);
574
- return nextArg({
575
- ...this.schema,
576
- ...normalized.setsSeparator ? { separator: normalized.separator } : {},
577
- split: normalized.split
578
- });
579
- }
580
- /**
581
- * Deduplicate the resolved values of a variadic arg, preserving first-seen
582
- * order. Applied after all sources resolve, using `SameValueZero` semantics.
583
- *
584
- * Available on a variadic arg of a list kind, so call it after `.variadic()`.
585
- *
586
- * @param value - Whether to deduplicate.
587
- * @defaultValue `true`
588
- * @returns The builder (for chaining).
589
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an arg that resolves to
590
- * one value or to a record.
591
- */
592
- unique(value = true) {
593
- if (this.schema.kind === "keyValue" || this.schema.variadic !== true) assertValidArgDefinition(this.schema.kind, {
594
- ...this.schema,
595
- unique: true
596
- });
597
- return nextArg({
598
- ...this.schema,
599
- unique: value
600
- });
601
- }
602
- /**
603
- * Set how a repeated key combines.
604
- *
605
- * @param policy - `'last'` (default), `'first'`, or `'error'`.
606
- * @returns The builder (for chaining).
607
- * @throws {CLIError} With code `'INVALID_SCHEMA'` on an arg that is not
608
- * `arg.keyValue()`.
609
- *
610
- * @example
611
- * ```ts
612
- * arg.keyValue().variadic().duplicateKeys('error').env('VARS')
613
- * // $ VARS='A=1,A=2' mycli run
614
- * // # → Duplicate key '<redacted>' from env VARS for argument <vars> (CONSTRAINT_VIOLATED)
615
- * ```
616
- */
617
- duplicateKeys(policy) {
618
- return nextArg({
619
- ...this.schema,
620
- duplicateKeys: policy
621
- });
622
- }
623
- /**
624
- * Validate the resolved value with a Standard Schema v1 validator.
625
- *
626
- * On a single-value builder the validator sees each value; on a builder that
627
- * already aggregates (`.variadic()` or `arg.keyValue()`) it sees the
628
- * completed array or record, after every element passed its own validator.
629
- *
630
- * The builder this is called on is what decides, so where the call sits
631
- * relative to `.variadic()` chooses between the two.
632
- *
633
- * @param schema - A Standard Schema v1 validator.
634
- * @returns The builder (for chaining).
635
- *
636
- * @example
637
- * ```ts
638
- * import { z } from 'zod';
639
- * arg.string().standard(z.string().min(1)).variadic() // each element
640
- * arg.string().variadic().standard(z.array(z.string())) // the whole array
641
- * ```
642
- */
643
- standard(schema) {
644
- const aggregate = isCollection(argCardinality(this.schema));
645
- return nextArg({
646
- ...this.schema,
647
- ...aggregate ? { aggregateStandard: schema } : { standard: schema }
648
- });
649
- }
650
- /**
651
- * Let this arg read its value from piped stdin.
652
- *
653
- * An explicit `-` in the arg's slot is CLI-sourced with bytes from stdin and
654
- * keeps CLI precedence. An absent positional takes the stdin fallback stage,
655
- * which sits between CLI and env, so an arg set in the environment still
656
- * reads stdin and stdin wins. The whole buffer becomes the value, byte for
657
- * byte for a string arg; every other kind drops the single line terminator a
658
- * pipe appends before decoding, and `{ trim: true }` drops it for a string
659
- * arg too.
660
- *
661
- * On an arg that aggregates, a `-` among the tail tokens splices what the
662
- * buffer decodes to into that position, so `mycli build a - b` over
663
- * `'x\ny\n'` collects `['a', 'x', 'y', 'b']`. Each `-` stands for the whole
664
- * source, so two of them splice the buffer twice. A `-` typed beside other
665
- * tokens with nothing piped fails with `MISSING_STDIN`; a tail of nothing but
666
- * `-` falls through to the later sources.
667
- *
668
- * A stdin-enabled arg cannot receive a literal `-` as its value, since the
669
- * token names the source.
670
- *
671
- * One command may declare a single exclusive stdin consumer; pass
672
- * `{ consume: 'broadcast' }` on every input that should share the buffer.
673
- *
674
- * @param options - When to read stdin, how to share it, and whether to trim.
675
- * @returns The builder (for chaining).
676
- *
677
- * @example
678
- * ```ts
679
- * arg.string().describe('Input text').stdin()
680
- * // $ echo "hello" | mycli transform → input = 'hello\n' (from stdin)
681
- * // $ mycli transform - → input reads stdin
682
- * // $ mycli transform "hello" → input = 'hello' (from CLI)
683
- *
684
- * arg.string().stdin({ when: 'dash' })
685
- * // only an explicit `-` reads stdin
686
- *
687
- * arg.path({ mustExist: true }).stdin({ trim: true })
688
- * // $ echo ./dist | mycli clean → path = './dist', checked on disk
689
- * ```
690
- */
691
- stdin(options) {
692
- return new ArgBuilder({
693
- ...this.schema,
694
- stdin: normalizeStdinBinding(options)
695
- });
696
- }
697
- /**
698
- * Bind to an environment variable.
699
- *
700
- * When the arg is not provided on the CLI or by stdin, the resolver checks
701
- * this env var before config, prompt, and the default value. The env string
702
- * is coerced to the arg's declared kind (passthrough for strings, parsed
703
- * for numbers, run through `parseFn` for custom args).
704
- *
705
- * Resolution order when extra sources are configured:
706
- * **CLI → stdin → env → config → prompt → default**.
707
- *
708
- * Help output shows `[env: VAR]` next to the arg description.
709
- *
710
- * @param varName - Environment variable name (e.g. `'DEPLOY_TARGET'`).
711
- * @returns The builder (for chaining).
712
- *
713
- * @example
714
- * ```ts
715
- * command('deploy')
716
- * .arg('target', arg.string().env('DEPLOY_TARGET').describe('Deploy target'))
717
- * .arg('port', arg.number().env('PORT').default(3000))
718
- * .action(({ args }) => {
719
- * console.log(args.target); // from CLI, $DEPLOY_TARGET, or error
720
- * console.log(args.port); // from CLI, $PORT, or 3000
721
- * });
722
- * ```
723
- */
724
- env(varName) {
725
- return new ArgBuilder({
726
- ...this.schema,
727
- envVar: varName
728
- });
729
- }
730
- /**
731
- * Bind to a dotted config path.
732
- *
733
- * The config value is read after CLI, stdin, and env, and is coerced to the
734
- * arg's declared kind the same way a flag's config value is.
735
- *
736
- * @param path - Dotted config key (e.g. `'deploy.region'`).
737
- * @returns The builder (for chaining).
738
- *
739
- * @example
740
- * ```ts
741
- * arg.string().config('deploy.region').default('us-east-1')
742
- * // Config file: { "deploy": { "region": "eu-west-1" } }
743
- * // $ mycli deploy → region = 'eu-west-1'
744
- * // $ mycli deploy ap-south-1 → CLI positional wins
745
- * ```
746
- */
747
- config(path) {
748
- return new ArgBuilder({
749
- ...this.schema,
750
- configPath: path
751
- });
752
- }
753
- /**
754
- * Attach interactive prompt configuration.
755
- *
756
- * When CLI, stdin, env, and config all produce nothing, the prompt engine
757
- * uses this config to ask the user. In non-interactive contexts the prompt
758
- * is skipped and resolution falls through to the default or the missing-arg
759
- * error.
760
- *
761
- * The compatible kinds follow the value and the cardinality: a variadic arg
762
- * takes the `multiselect` a `flag.array()` takes, and every other arg takes
763
- * what its kind takes on the flag surface.
764
- *
765
- * @param config - {@link PromptConfig} describing the interactive prompt.
766
- * @returns The builder (for chaining).
767
- *
768
- * @example
769
- * ```ts
770
- * arg.string().prompt({ kind: 'input', message: 'Target:' })
771
- * // $ mycli deploy → prompts "Target:"
772
- * // $ mycli deploy production → skips the prompt
773
- *
774
- * arg.string().variadic().prompt({ kind: 'multiselect', message: 'Targets:' })
775
- * ```
776
- */
777
- prompt(config) {
778
- return new ArgBuilder({
779
- ...this.schema,
780
- prompt: config
781
- });
782
- }
783
- /**
784
- * Human-readable description shown in help output.
785
- *
786
- * @param description - Text displayed next to the arg in `--help`.
787
- * @returns The builder (for chaining).
788
- *
789
- * @example
790
- * ```ts
791
- * arg.string().describe('Deploy target')
792
- *
793
- * // Help output:
794
- * // Arguments:
795
- * // <target> Deploy target
796
- * ```
797
- */
798
- describe(description) {
799
- return new ArgBuilder({
800
- ...this.schema,
801
- description
802
- });
803
- }
804
- /**
805
- * Mark this arg as deprecated.
806
- *
807
- * When used, a warning is emitted to stderr. Help text shows
808
- * `[deprecated]` or `[deprecated: <reason>]`.
809
- *
810
- * Does not change the arg's type-level config — it's metadata only.
811
- *
812
- * @param message - Optional migration reason/guidance.
813
- * @returns The builder (for chaining).
814
- *
815
- * @example
816
- * ```ts
817
- * arg.string().deprecated() // generic
818
- * arg.string().deprecated('use --target flag instead') // with guidance
819
- *
820
- * // Help output:
821
- * // Arguments:
822
- * // <target> Deploy target [deprecated: use --target flag instead]
823
- * ```
824
- */
825
- deprecated(message) {
826
- return new ArgBuilder({
827
- ...this.schema,
828
- deprecated: message ?? true
829
- });
830
- }
831
- /**
832
- * Require an integer value. Composes with other numeric constraints.
833
- *
834
- * @param value - Whether to require an integer.
835
- * @defaultValue `true`
836
- * @returns The builder (for chaining).
837
- *
838
- * @example
839
- * ```ts
840
- * arg.number().int() // rejects 3.7, accepts 3
841
- * arg.number({ int: true }).int(false) // re-allows non-integers
842
- * ```
843
- */
844
- int(value = true) {
845
- return nextArg({
846
- ...this.schema,
847
- numberConstraints: {
848
- ...this.schema.numberConstraints,
849
- int: value
850
- }
851
- });
852
- }
853
- /**
854
- * Set an inclusive lower bound. Composes with other numeric constraints;
855
- * a later call overrides an earlier `min` (including one from the options
856
- * object).
857
- *
858
- * @param value - Inclusive minimum.
859
- * @returns The builder (for chaining).
860
- *
861
- * @example
862
- * ```ts
863
- * arg.number().min(0) // rejects -1, accepts 0
864
- * arg.number({ min: 0 }).min(5) // effective min is 5
865
- * ```
866
- */
867
- min(value) {
868
- const numberConstraints = {
869
- ...this.schema.numberConstraints,
870
- min: value
871
- };
872
- assertNumberConstraints(numberConstraints);
873
- return nextArg({
874
- ...this.schema,
875
- numberConstraints
876
- });
877
- }
878
- /**
879
- * Set an inclusive upper bound. Composes with other numeric constraints;
880
- * a later call overrides an earlier `max`.
881
- *
882
- * @param value - Inclusive maximum.
883
- * @returns The builder (for chaining).
884
- *
885
- * @example
886
- * ```ts
887
- * arg.number().max(100) // rejects 101, accepts 100
888
- * ```
889
- */
890
- max(value) {
891
- const numberConstraints = {
892
- ...this.schema.numberConstraints,
893
- max: value
894
- };
895
- assertNumberConstraints(numberConstraints);
896
- return nextArg({
897
- ...this.schema,
898
- numberConstraints
899
- });
900
- }
901
- /**
902
- * Require (or, with `false`, allow) a finite value. Finiteness is enforced
903
- * by default, so this is mainly used as `.finite(false)` to re-allow
904
- * `Infinity` / `-Infinity`.
905
- *
906
- * @param allow - Whether to require a finite value.
907
- * @defaultValue `true`
908
- * @returns The builder (for chaining).
909
- *
910
- * @example
911
- * ```ts
912
- * arg.number().finite(false) // accepts Infinity
913
- * ```
914
- */
915
- finite(allow = true) {
916
- return nextArg({
917
- ...this.schema,
918
- numberConstraints: {
919
- ...this.schema.numberConstraints,
920
- finite: allow
921
- }
922
- });
923
- }
924
- /**
925
- * Reject empty strings. Composes with other string constraints.
926
- *
927
- * @param value - Whether to reject empty strings.
928
- * @defaultValue `true`
929
- * @returns The builder (for chaining).
930
- *
931
- * @example
932
- * ```ts
933
- * arg.string().nonEmpty() // rejects '', accepts 'x'
934
- * ```
935
- */
936
- nonEmpty(value = true) {
937
- return nextArg({
938
- ...this.schema,
939
- stringConstraints: {
940
- ...this.schema.stringConstraints,
941
- nonEmpty: value
942
- }
943
- });
944
- }
945
- /**
946
- * Set an inclusive minimum length (UTF-16 code units). Composes with other
947
- * string constraints; a later call overrides an earlier `minLength`.
948
- *
949
- * @param value - Inclusive minimum length.
950
- * @returns The builder (for chaining).
951
- *
952
- * @example
953
- * ```ts
954
- * arg.string().minLength(3) // rejects 'ab', accepts 'abc'
955
- * ```
956
- */
957
- minLength(value) {
958
- const stringConstraints = {
959
- ...this.schema.stringConstraints,
960
- minLength: value
961
- };
962
- assertStringConstraints(stringConstraints);
963
- return nextArg({
964
- ...this.schema,
965
- stringConstraints
966
- });
967
- }
968
- /**
969
- * Set an inclusive maximum length (UTF-16 code units). Composes with other
970
- * string constraints; a later call overrides an earlier `maxLength`.
971
- *
972
- * @param value - Inclusive maximum length.
973
- * @returns The builder (for chaining).
974
- *
975
- * @example
976
- * ```ts
977
- * arg.string().maxLength(8) // rejects 9+ chars
978
- * ```
979
- */
980
- maxLength(value) {
981
- const stringConstraints = {
982
- ...this.schema.stringConstraints,
983
- maxLength: value
984
- };
985
- assertStringConstraints(stringConstraints);
986
- return nextArg({
987
- ...this.schema,
988
- stringConstraints
989
- });
990
- }
991
- /**
992
- * Require the value to match a regular expression. Anchor with `^`/`$`
993
- * for full-string matching. Composes with other string constraints.
994
- *
995
- * @param value - Pattern the value must match.
996
- * @returns The builder (for chaining).
997
- *
998
- * @example
999
- * ```ts
1000
- * arg.string().pattern(/^ghp_/) // rejects 'abc', accepts 'ghp_x'
1001
- * ```
1002
- */
1003
- pattern(value) {
1004
- return nextArg({
1005
- ...this.schema,
1006
- stringConstraints: {
1007
- ...this.schema.stringConstraints,
1008
- pattern: value
1009
- }
1010
- });
1011
- }
1012
- };
1013
- /**
1014
- * Continue a builder chain, rejecting a schema the change just invalidated.
1015
- *
1016
- * The `this` constraint on each modifier states to the compiler which kinds
1017
- * carry the field it sets; this states the same rule to a caller who reaches
1018
- * the builder from JavaScript, with the error {@link createArgSchema} already
1019
- * gives, so what a builder produces is always a definition the framework can
1020
- * read back.
1021
- *
1022
- * A constraint added after `.default()` still governs the default, so the
1023
- * verdict is the same whichever order the chain was written in.
1024
- *
1025
- * @param schema - The schema the modifier produced.
1026
- * @returns A builder over that schema.
1027
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when the field does not belong
1028
- * on the arg, or `'INVALID_DEFAULT'` when the default no longer holds.
1029
- * @internal
1030
- */
1031
- function nextArg(schema) {
1032
- assertValidArgDefinition(schema.kind, schema);
1033
- assertValidArgDefault(void 0, schema);
1034
- return new ArgBuilder(schema);
1035
- }
1036
- /**
1037
- * Positional argument schema factory.
1038
- *
1039
- * Entry point for defining args on a command. Use `arg.<kind>()` to create
1040
- * an {@linkcode ArgBuilder}, then chain modifiers and pass the result to
1041
- * `command().arg(name, builder)`.
1042
- *
1043
- * Six base kinds are available:
1044
- * - `arg.string()` — raw string (most common)
1045
- * - `arg.number()` — parsed to number, errors on NaN
1046
- * - `arg.boolean()` reads an explicit true/false token
1047
- * - `arg.enum(values)` — constrained to listed literals
1048
- * - `arg.keyValue()` merges `KEY=VALUE` tokens into a record
1049
- * - `arg.custom(fn)` — arbitrary parse function, infers return type
1050
- *
1051
- * Five sugar factories build on them, mirroring their flag counterparts:
1052
- * - `arg.url()` parses to `URL`, with an optional protocol allowlist
1053
- * - `arg.path()` keeps the string and adds optional filesystem checks
1054
- * - `arg.date()` parses strict ISO-8601 to `Date`
1055
- * - `arg.duration()` resolves `'1h30m'` and friends to milliseconds
1056
- * - `arg.bytes()` resolves `'512mb'` and friends to bytes
1057
- *
1058
- * @example
1059
- * ```ts
1060
- * import { command, arg } from '@kjanat/dreamcli';
1061
- *
1062
- * command('deploy')
1063
- * .arg('target', arg.string().env('DEPLOY_TARGET').describe('Where to deploy'))
1064
- * .arg('port', arg.number().env('PORT').default(3000))
1065
- * .action(({ args }) => {
1066
- * console.log(`Deploying to ${args.target} on port ${args.port}`);
1067
- * });
1068
- *
1069
- * // $ mycli deploy production 8080 → target='production', port=8080
1070
- * // $ DEPLOY_TARGET=staging mycli deploy → target='staging', port=3000
1071
- * ```
1072
- */
1073
- const arg = {
1074
- string(constraints) {
1075
- if (constraints !== void 0) assertStringConstraints(constraints);
1076
- return new ArgBuilder(createArgSchema("string", valueDefinitionFields(stringValue(constraints))));
1077
- },
1078
- number(constraints) {
1079
- if (constraints !== void 0) assertNumberConstraints(constraints);
1080
- return new ArgBuilder(createArgSchema("number", valueDefinitionFields(numberValue(constraints))));
1081
- },
1082
- boolean() {
1083
- return new ArgBuilder(createArgSchema("boolean", valueDefinitionFields(booleanValue())));
1084
- },
1085
- keyValue(element) {
1086
- if (element !== void 0) assertArgElementBuilder("keyValue", element);
1087
- return new ArgBuilder(createArgSchema("keyValue", {
1088
- valueHint: "key=value",
1089
- ...element !== void 0 ? { elementSchema: element.schema } : {}
1090
- }));
1091
- },
1092
- enum(values) {
1093
- return new ArgBuilder(createArgSchema("enum", { enumValues: values }));
1094
- },
1095
- custom(parseFnOrSchema) {
1096
- if (isStandardSchemaV1(parseFnOrSchema)) return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(standardValue(parseFnOrSchema))));
1097
- return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(stringParsedValue(parseFnOrSchema))));
1098
- },
1099
- url(options) {
1100
- return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(urlValue(options))));
1101
- },
1102
- path(options) {
1103
- return new ArgBuilder(createArgSchema("string", valueDefinitionFields(pathValue(options))));
1104
- },
1105
- date(options) {
1106
- return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(dateValue(options))));
1107
- },
1108
- duration() {
1109
- return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(durationValue())));
1110
- },
1111
- bytes() {
1112
- return new ArgBuilder(createArgSchema("custom", valueDefinitionFields(bytesValue())));
1113
- }
1114
- };
1115
- /**
1116
- * Reject a collection factory handed something other than an arg builder.
1117
- *
1118
- * The types demand one, so this catches an untyped JavaScript caller before the
1119
- * factory reads `.schema` off a value that has none.
1120
- *
1121
- * @param factory - Name of the factory being called.
1122
- * @param element - What the caller passed as the element.
1123
- * @throws {CLIError} With code `'INVALID_SCHEMA'` when it is not an
1124
- * {@link ArgBuilder}.
1125
- */
1126
- function assertArgElementBuilder(factory, element) {
1127
- if (element instanceof ArgBuilder) return;
1128
- throw new CLIError(`arg.${factory}() requires an element builder`, {
1129
- code: "INVALID_SCHEMA",
1130
- details: {
1131
- factory,
1132
- field: "element",
1133
- received: typeof element
1134
- },
1135
- suggest: `Pass an element builder, as in arg.${factory}(arg.string())`
1136
- });
1137
- }
1138
- //#endregion
1139
- export { ARG_KINDS, ArgBuilder, arg, createArgSchema };