@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.d.mts +7 -3
  66. package/dist/version.mjs +7 -1
  67. package/package.json +21 -26
  68. package/src/core/cli/dispatch.ts +0 -355
  69. package/src/core/cli/help-links.ts +0 -82
  70. package/src/core/cli/index.ts +0 -1614
  71. package/src/core/cli/planner.ts +0 -656
  72. package/src/core/cli/plugin.ts +0 -117
  73. package/src/core/cli/propagate.ts +0 -97
  74. package/src/core/cli/root-help.ts +0 -342
  75. package/src/core/cli/root-surface.ts +0 -87
  76. package/src/core/cli/runtime-preflight.ts +0 -456
  77. package/src/core/completion/index.ts +0 -138
  78. package/src/core/completion/shells/bash.ts +0 -459
  79. package/src/core/completion/shells/fish.ts +0 -259
  80. package/src/core/completion/shells/powershell.ts +0 -439
  81. package/src/core/completion/shells/shared.ts +0 -310
  82. package/src/core/completion/shells/zsh.ts +0 -381
  83. package/src/core/config/index.ts +0 -417
  84. package/src/core/config/package-json.ts +0 -560
  85. package/src/core/errors/index.ts +0 -193
  86. package/src/core/execution/index.ts +0 -265
  87. package/src/core/help/ansi.ts +0 -144
  88. package/src/core/help/index.ts +0 -563
  89. package/src/core/json-schema/index.ts +0 -910
  90. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  91. package/src/core/output/activity.ts +0 -575
  92. package/src/core/output/bind.ts +0 -59
  93. package/src/core/output/contracts.ts +0 -194
  94. package/src/core/output/display-value.ts +0 -48
  95. package/src/core/output/index.ts +0 -704
  96. package/src/core/output/renderers.ts +0 -125
  97. package/src/core/output/writer.ts +0 -46
  98. package/src/core/parse/index.ts +0 -742
  99. package/src/core/prompt/index.ts +0 -623
  100. package/src/core/resolve/args.ts +0 -144
  101. package/src/core/resolve/coerce.ts +0 -500
  102. package/src/core/resolve/config.ts +0 -26
  103. package/src/core/resolve/contracts.ts +0 -135
  104. package/src/core/resolve/errors.ts +0 -227
  105. package/src/core/resolve/flags.ts +0 -269
  106. package/src/core/resolve/index.ts +0 -108
  107. package/src/core/resolve/property.ts +0 -99
  108. package/src/core/schema/activity.ts +0 -240
  109. package/src/core/schema/arg.ts +0 -841
  110. package/src/core/schema/command.ts +0 -1500
  111. package/src/core/schema/flag.ts +0 -917
  112. package/src/core/schema/index.ts +0 -96
  113. package/src/core/schema/middleware.ts +0 -171
  114. package/src/core/schema/number-constraints.ts +0 -153
  115. package/src/core/schema/prompt.ts +0 -171
  116. package/src/core/schema/run.ts +0 -198
  117. package/src/core/schema-dsl/index.ts +0 -109
  118. package/src/core/schema-dsl/parse.ts +0 -262
  119. package/src/core/schema-dsl/runtime.ts +0 -609
  120. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  121. package/src/core/testkit/index.ts +0 -147
  122. package/src/index.ts +0 -181
  123. package/src/runtime/adapter.ts +0 -303
  124. package/src/runtime/auto.ts +0 -86
  125. package/src/runtime/bun.ts +0 -48
  126. package/src/runtime/deno.ts +0 -367
  127. package/src/runtime/detect.ts +0 -105
  128. package/src/runtime/index.ts +0 -21
  129. package/src/runtime/node-builtins.d.ts +0 -27
  130. package/src/runtime/node.ts +0 -289
  131. package/src/runtime/paths.ts +0 -64
  132. package/src/runtime/support.ts +0 -77
  133. package/src/runtime.ts +0 -31
  134. package/src/schema.ts +0 -16
  135. package/src/strings.ts +0 -34
  136. package/src/testkit.ts +0 -25
  137. package/src/version.ts +0 -20
@@ -1,841 +0,0 @@
1
- /**
2
- * Positional argument schema builder with full type inference.
3
- *
4
- * Each factory (`arg.string()`, `arg.number()`, `arg.enum()`, `arg.custom()`) returns an
5
- * immutable {@linkcode ArgBuilder} whose generic parameter tracks the value type,
6
- * presence state, and variadic flag through the fluent chain.
7
- *
8
- * @module dreamcli/core/schema/arg
9
- */
10
-
11
- import { assertNumberConstraints, type NumberConstraints } from './number-constraints.ts';
12
-
13
- // --- Type-level configuration (phantom state tracked through the chain)
14
-
15
- /** All arg presence states as a runtime array. */
16
- const ARG_PRESENCES = ['required', 'optional', 'defaulted'] as const;
17
-
18
- /**
19
- * Presence describes whether a positional arg is guaranteed to exist when the
20
- * action handler runs:
21
- *
22
- * - `'required'` — must be supplied; error if missing (default)
23
- * - `'optional'` — may be `undefined` if not supplied
24
- * - `'defaulted'` — always present (falls back to default value)
25
- */
26
- type ArgPresence = (typeof ARG_PRESENCES)[number];
27
-
28
- /**
29
- * Compile-time state carried through the builder chain.
30
- */
31
- interface ArgConfig {
32
- /** The resolved value type (e.g. `string`, `number`, custom). */
33
- readonly valueType: unknown;
34
- /** Whether the arg is required, optional, or has a default. */
35
- readonly presence: ArgPresence;
36
- /** Whether this arg consumes remaining positionals. */
37
- readonly variadic: boolean;
38
- /** The runtime kind discriminator, mirroring {@link ArgKind}. */
39
- readonly argKind: ArgKind;
40
- }
41
-
42
- // --- Type-level helpers
43
-
44
- /**
45
- * Advanced type helper used by {@linkcode ArgBuilder} modifiers to replace presence.
46
- * Most consumers rely on inference and never reference this directly.
47
- */
48
- type WithArgPresence<C extends ArgConfig, P extends ArgPresence> = {
49
- readonly valueType: C['valueType'];
50
- readonly presence: P;
51
- readonly variadic: C['variadic'];
52
- readonly argKind: C['argKind'];
53
- };
54
-
55
- /**
56
- * Advanced type helper used by {@linkcode ArgBuilder.variadic | ArgBuilder.variadic()}.
57
- * Most consumers rely on inference and never reference this directly.
58
- */
59
- type WithVariadic<C extends ArgConfig> = {
60
- readonly valueType: C['valueType'];
61
- readonly presence: C['presence'];
62
- readonly variadic: true;
63
- readonly argKind: C['argKind'];
64
- };
65
-
66
- /**
67
- * Compute the final value type from config — this is what handlers receive.
68
- *
69
- * Advanced type helper: this powers {@link InferArg} and action-handler
70
- * inference. Most apps do not need to mention it explicitly.
71
- *
72
- * Variadic args always produce an array. Non-variadic:
73
- * - `'optional'` → `T | undefined`
74
- * - `'required'` → `T`
75
- * - `'defaulted'` → `T`
76
- */
77
- type ResolvedArgValue<C extends ArgConfig> = C['variadic'] extends true
78
- ? C['valueType'][]
79
- : C['presence'] extends 'optional'
80
- ? C['valueType'] | undefined
81
- : C['valueType'];
82
-
83
- /** Extract the resolved value type from an {@linkcode ArgBuilder}. */
84
- type InferArg<B> = B extends ArgBuilder<infer C extends ArgConfig> ? ResolvedArgValue<C> : never;
85
-
86
- /** Extract resolved value types from a record of builders. */
87
- type InferArgs<T extends Record<string, ArgBuilder<ArgConfig>>> = {
88
- [K in keyof T]: InferArg<T[K]>;
89
- };
90
-
91
- // --- Runtime schema data
92
-
93
- /** All arg kind discriminators as a runtime array. */
94
- const ARG_KINDS = ['string', 'number', 'enum', 'custom'] as const;
95
-
96
- /** Discriminator for the kind of value an arg accepts. */
97
- type ArgKind = (typeof ARG_KINDS)[number];
98
-
99
- /** Custom parse function for `arg.custom()`. */
100
- type ArgParseFn<T> = (raw: string) => T;
101
-
102
- /**
103
- * The runtime descriptor stored inside every {@linkcode ArgBuilder}. Consumers (parser,
104
- * help generator) read this to understand the arg's shape without touching
105
- * generics.
106
- */
107
- interface ArgSchema {
108
- /** What kind of value this arg accepts. */
109
- readonly kind: ArgKind;
110
- /** Current presence state. */
111
- readonly presence: ArgPresence;
112
- /** Whether this arg consumes all remaining positionals. */
113
- readonly variadic: boolean;
114
- /**
115
- * Whether this arg may read from stdin during resolution.
116
- * @defaultValue `false`
117
- */
118
- readonly stdinMode: boolean;
119
- /** Runtime default value (if any). */
120
- readonly defaultValue: unknown;
121
- /** Human-readable description for help text. */
122
- readonly description: string | undefined;
123
- /**
124
- * Environment variable name for env resolution.
125
- *
126
- * When set and the CLI value is absent, the resolver reads this env var
127
- * and coerces the string to the arg's declared kind.
128
- *
129
- * @see {@link ArgBuilder.env} for the builder method.
130
- */
131
- readonly envVar: string | undefined;
132
- /** Allowed literal values when `kind === 'enum'`. */
133
- readonly enumValues: readonly string[] | undefined;
134
- /**
135
- * Numeric constraints when `kind === 'number'` (`undefined` otherwise).
136
- *
137
- * Enforced at the parse and resolution boundaries. `finite` defaults to
138
- * `true`, so `Infinity` is rejected even when no constraints object is set.
139
- */
140
- readonly numberConstraints: NumberConstraints | undefined;
141
- /** Custom parse function (only when `kind === 'custom'`). */
142
- readonly parseFn: ArgParseFn<unknown> | undefined;
143
- /**
144
- * Deprecation marker.
145
- *
146
- * - `undefined` — not deprecated (default)
147
- * - `true` — deprecated with no migration message
148
- * - `string` — deprecated with a reason/migration message
149
- *
150
- * When a deprecated arg is used, a warning is emitted to stderr.
151
- * Help text shows `[deprecated]` or `[deprecated: <reason>]`.
152
- */
153
- readonly deprecated: string | true | undefined;
154
- }
155
-
156
- /**
157
- * Create a raw {@link ArgSchema} object with sensible defaults.
158
- *
159
- * Most consumers should prefer the higher-level {@link arg} factory, which
160
- * returns an immutable {@link ArgBuilder} with type inference and fluent
161
- * modifiers. `createArgSchema()` exists for advanced schema composition,
162
- * targeted tests, or custom builders that need the plain runtime descriptor.
163
- *
164
- * `overrides` are shallow-merged on top of the default shape, so callers are
165
- * responsible for preserving invariants such as variadic ordering and
166
- * compatible `parseFn` / `kind` combinations.
167
- *
168
- * @param kind - Discriminator for the value type this arg accepts.
169
- * @param overrides - Partial schema fields shallow-merged onto defaults.
170
- * @returns A fully populated {@link ArgSchema}.
171
- *
172
- * @example
173
- * ```ts
174
- * const schema = createArgSchema('custom', {
175
- * description: 'Hex color',
176
- * parseFn: (raw) => `#${raw}`,
177
- * });
178
- * ```
179
- */
180
- function createArgSchema(kind: ArgKind, overrides?: Partial<ArgSchema>): ArgSchema {
181
- return {
182
- kind,
183
- presence: 'required',
184
- variadic: false,
185
- stdinMode: false,
186
- defaultValue: undefined,
187
- description: undefined,
188
- envVar: undefined,
189
- enumValues: undefined,
190
- numberConstraints: undefined,
191
- parseFn: undefined,
192
- deprecated: undefined,
193
- ...overrides,
194
- };
195
- }
196
-
197
- // --- ArgBuilder — immutable builder with type-level tracking
198
-
199
- /**
200
- * Immutable positional argument schema builder.
201
- *
202
- * The type parameter `C` is a phantom that tracks the value type, presence,
203
- * and variadic state through the fluent chain. Each modifier returns a **new**
204
- * builder — the original is never mutated.
205
- *
206
- * @example
207
- * ```ts
208
- * // Full command with multiple args and modifiers
209
- * import { command, arg } from '@kjanat/dreamcli';
210
- *
211
- * command('deploy')
212
- * .arg('target', arg.string()
213
- * .env('DEPLOY_TARGET')
214
- * .describe('Deploy target'))
215
- * .arg('port', arg.number()
216
- * .env('PORT')
217
- * .default(3000)
218
- * .describe('Port number'))
219
- * .arg('files', arg.string()
220
- * .variadic()
221
- * .optional()
222
- * .describe('Extra config files'))
223
- * .action(({ args }) => {
224
- * args.target; // string (required, from CLI or $DEPLOY_TARGET)
225
- * args.port; // number (defaulted, from CLI, $PORT, or 3000)
226
- * args.files; // string[] (optional variadic)
227
- * });
228
- * ```
229
- *
230
- * @example
231
- * ```ts
232
- * // Type inference
233
- * const target = arg.string();
234
- * type T = InferArg<typeof target>; // string
235
- *
236
- * const opt = arg.string().optional();
237
- * type O = InferArg<typeof opt>; // string | undefined
238
- *
239
- * const files = arg.string().variadic();
240
- * type F = InferArg<typeof files>; // string[]
241
- * ```
242
- */
243
- class ArgBuilder<C extends ArgConfig> {
244
- /** @internal Runtime schema descriptor. */
245
- readonly schema: ArgSchema;
246
-
247
- /**
248
- * @internal Type brand — exists only in the type system (`declare`
249
- * produces no runtime property). Used by {@linkcode InferArg} / {@linkcode InferArgs}.
250
- */
251
- declare readonly _config: C;
252
-
253
- /**
254
- * Create an arg builder from a pre-built schema descriptor.
255
- *
256
- * @param schema - Runtime descriptor for this positional argument.
257
- */
258
- constructor(schema: ArgSchema) {
259
- this.schema = schema;
260
- }
261
-
262
- // -- Presence modifiers --------------------------------------------------
263
-
264
- /**
265
- * Mark the arg as required (this is the default for positional args).
266
- * Produces an error if no value resolves from any configured source
267
- * (CLI → stdin → env → default).
268
- *
269
- * @example
270
- * ```ts
271
- * arg.string().required() // explicit, same as default
272
- *
273
- * // In a command — omitting <target> causes a ValidationError:
274
- * command('deploy')
275
- * .arg('target', arg.string().required().describe('Deploy target'))
276
- * // $ mycli deploy
277
- * // Error: Missing required argument <target>
278
- * ```
279
- *
280
- * @returns The builder (for chaining).
281
- */
282
- required(): ArgBuilder<WithArgPresence<C, 'required'>> {
283
- return new ArgBuilder({
284
- ...this.schema,
285
- presence: 'required',
286
- });
287
- }
288
-
289
- /**
290
- * Mark the arg as optional. Handlers receive `undefined` when absent.
291
- *
292
- * @example
293
- * ```ts
294
- * arg.string().optional()
295
- *
296
- * // In a command — handler receives `undefined` when omitted:
297
- * command('greet')
298
- * .arg('name', arg.string().optional().describe('Who to greet'))
299
- * .action(({ args }) => {
300
- * args.name; // string | undefined
301
- * });
302
- * // $ mycli greet → args.name is undefined
303
- * // $ mycli greet Alice → args.name is 'Alice'
304
- * ```
305
- *
306
- * @returns The builder (for chaining).
307
- */
308
- optional(): ArgBuilder<WithArgPresence<C, 'optional'>> {
309
- return new ArgBuilder({
310
- ...this.schema,
311
- presence: 'optional',
312
- });
313
- }
314
-
315
- /**
316
- * Provide a default value. The arg becomes "always present" — handlers
317
- * will never see `undefined`.
318
- *
319
- * The generic constraint `V extends C['valueType']` ensures the default
320
- * matches the arg's declared type.
321
- *
322
- * Resolution order when extra sources are configured: CLI → stdin → env → **default**.
323
- *
324
- * @param value - Fallback used when no CLI value or env var resolves.
325
- * @returns The builder (for chaining).
326
- *
327
- * @example
328
- * ```ts
329
- * arg.string().default('production')
330
- * arg.number().default(3000)
331
- *
332
- * // In a command — default kicks in when CLI and env are both absent:
333
- * command('deploy')
334
- * .arg('env', arg.string()
335
- * .env('DEPLOY_ENV')
336
- * .default('staging')
337
- * .describe('Target environment'))
338
- * .action(({ args }) => {
339
- * args.env; // string (never undefined)
340
- * });
341
- * // $ mycli deploy → 'staging' (default)
342
- * // $ DEPLOY_ENV=prod mycli deploy → 'prod' (env)
343
- * // $ mycli deploy production → 'production' (CLI)
344
- * ```
345
- */
346
- default<V extends C['valueType']>(value: V): ArgBuilder<WithArgPresence<C, 'defaulted'>> {
347
- return new ArgBuilder({
348
- ...this.schema,
349
- presence: 'defaulted',
350
- defaultValue: value,
351
- });
352
- }
353
-
354
- // -- Variadic modifier ---------------------------------------------------
355
-
356
- /**
357
- * Mark this arg as variadic — it consumes all remaining positional
358
- * arguments. The inferred type becomes `T[]`.
359
- *
360
- * A variadic arg must be the last positional in a command.
361
- *
362
- * @example
363
- * ```ts
364
- * arg.string().variadic()
365
- *
366
- * // In a command — collects all remaining positionals:
367
- * command('build')
368
- * .arg('entry', arg.string().describe('Main entry'))
369
- * .arg('extras', arg.string().variadic().optional().describe('Extra files'))
370
- * .action(({ args }) => {
371
- * args.entry; // string
372
- * args.extras; // string[]
373
- * });
374
- * // $ mycli build main.ts a.ts b.ts
375
- * // → entry = 'main.ts', extras = ['a.ts', 'b.ts']
376
- * ```
377
- *
378
- * @returns The builder (for chaining).
379
- */
380
- variadic(): ArgBuilder<WithVariadic<C>> {
381
- return new ArgBuilder({
382
- ...this.schema,
383
- variadic: true,
384
- });
385
- }
386
-
387
- /**
388
- * Allow this arg to resolve from stdin when CLI input is missing.
389
- *
390
- * Resolution order becomes: CLI value -> stdin -> env -> default.
391
- * Only one arg per command may enable stdin mode.
392
- *
393
- * @returns The builder (for chaining).
394
- *
395
- * @example
396
- * ```ts
397
- * arg.string().describe('Input text').stdin()
398
- * // $ echo "hello" | mycli transform → input = 'hello' (from stdin)
399
- * // $ mycli transform "hello" → input = 'hello' (from CLI)
400
- * ```
401
- */
402
- stdin(): ArgBuilder<C> {
403
- return new ArgBuilder({
404
- ...this.schema,
405
- stdinMode: true,
406
- });
407
- }
408
-
409
- // -- Resolution source modifiers ------------------------------------------
410
-
411
- /**
412
- * Bind to an environment variable.
413
- *
414
- * When the arg is not provided on the CLI, the resolver checks this
415
- * env var before falling back to the default value. The env string is
416
- * coerced to the arg's declared kind (passthrough for strings, parsed
417
- * for numbers, run through `parseFn` for custom args).
418
- *
419
- * Resolution order when extra sources are configured: **CLI → stdin → env → default**.
420
- *
421
- * Help output shows `[env: VAR]` next to the arg description.
422
- *
423
- * @param varName - Environment variable name (e.g. `'DEPLOY_TARGET'`).
424
- * @returns The builder (for chaining).
425
- *
426
- * @example
427
- * ```ts
428
- * command('deploy')
429
- * .arg('target', arg.string().env('DEPLOY_TARGET').describe('Deploy target'))
430
- * .arg('port', arg.number().env('PORT').default(3000))
431
- * .action(({ args }) => {
432
- * console.log(args.target); // from CLI, $DEPLOY_TARGET, or error
433
- * console.log(args.port); // from CLI, $PORT, or 3000
434
- * });
435
- * ```
436
- */
437
- env(varName: string): ArgBuilder<C> {
438
- return new ArgBuilder({
439
- ...this.schema,
440
- envVar: varName,
441
- });
442
- }
443
-
444
- // -- Metadata modifiers --------------------------------------------------
445
-
446
- /**
447
- * Human-readable description shown in help output.
448
- *
449
- * @param description - Text displayed next to the arg in `--help`.
450
- * @returns The builder (for chaining).
451
- *
452
- * @example
453
- * ```ts
454
- * arg.string().describe('Deploy target')
455
- *
456
- * // Help output:
457
- * // Arguments:
458
- * // <target> Deploy target
459
- * ```
460
- */
461
- describe(description: string): ArgBuilder<C> {
462
- return new ArgBuilder({
463
- ...this.schema,
464
- description,
465
- });
466
- }
467
-
468
- /**
469
- * Mark this arg as deprecated.
470
- *
471
- * When used, a warning is emitted to stderr. Help text shows
472
- * `[deprecated]` or `[deprecated: <reason>]`.
473
- *
474
- * Does not change the arg's type-level config — it's metadata only.
475
- *
476
- * @param message - Optional migration reason/guidance.
477
- * @returns The builder (for chaining).
478
- *
479
- * @example
480
- * ```ts
481
- * arg.string().deprecated() // generic
482
- * arg.string().deprecated('use --target flag instead') // with guidance
483
- *
484
- * // Help output:
485
- * // Arguments:
486
- * // <target> Deploy target [deprecated: use --target flag instead]
487
- * ```
488
- */
489
- deprecated(message?: string): ArgBuilder<C> {
490
- return new ArgBuilder({
491
- ...this.schema,
492
- deprecated: message ?? true,
493
- });
494
- }
495
-
496
- // -- Numeric constraint modifiers ----------------------------------------
497
- //
498
- // Compile-time guarded via a `this` parameter so they are only callable on
499
- // number-kind builders. They merge onto the single `numberConstraints`
500
- // representation, overriding any value set by `arg.number({ … })`.
501
-
502
- /**
503
- * Require an integer value. Composes with other numeric constraints.
504
- *
505
- * @param value - Whether to require an integer.
506
- * @defaultValue `true`
507
- * @returns The builder (for chaining).
508
- *
509
- * @example
510
- * ```ts
511
- * arg.number().int() // rejects 3.7, accepts 3
512
- * arg.number({ int: true }).int(false) // re-allows non-integers
513
- * ```
514
- */
515
- int(this: ArgBuilder<C & { readonly argKind: 'number' }>, value = true): ArgBuilder<C> {
516
- return new ArgBuilder({
517
- ...this.schema,
518
- numberConstraints: { ...this.schema.numberConstraints, int: value },
519
- });
520
- }
521
-
522
- /**
523
- * Set an inclusive lower bound. Composes with other numeric constraints;
524
- * a later call overrides an earlier `min` (including one from the options
525
- * object).
526
- *
527
- * @param value - Inclusive minimum.
528
- * @returns The builder (for chaining).
529
- *
530
- * @example
531
- * ```ts
532
- * arg.number().min(0) // rejects -1, accepts 0
533
- * arg.number({ min: 0 }).min(5) // effective min is 5
534
- * ```
535
- */
536
- min(this: ArgBuilder<C & { readonly argKind: 'number' }>, value: number): ArgBuilder<C> {
537
- const numberConstraints = { ...this.schema.numberConstraints, min: value };
538
- assertNumberConstraints(numberConstraints);
539
- return new ArgBuilder({ ...this.schema, numberConstraints });
540
- }
541
-
542
- /**
543
- * Set an inclusive upper bound. Composes with other numeric constraints;
544
- * a later call overrides an earlier `max`.
545
- *
546
- * @param value - Inclusive maximum.
547
- * @returns The builder (for chaining).
548
- *
549
- * @example
550
- * ```ts
551
- * arg.number().max(100) // rejects 101, accepts 100
552
- * ```
553
- */
554
- max(this: ArgBuilder<C & { readonly argKind: 'number' }>, value: number): ArgBuilder<C> {
555
- const numberConstraints = { ...this.schema.numberConstraints, max: value };
556
- assertNumberConstraints(numberConstraints);
557
- return new ArgBuilder({ ...this.schema, numberConstraints });
558
- }
559
-
560
- /**
561
- * Require (or, with `false`, allow) a finite value. Finiteness is enforced
562
- * by default, so this is mainly used as `.finite(false)` to re-allow
563
- * `Infinity` / `-Infinity`.
564
- *
565
- * @param allow - Whether to require a finite value.
566
- * @defaultValue `true`
567
- * @returns The builder (for chaining).
568
- *
569
- * @example
570
- * ```ts
571
- * arg.number().finite(false) // accepts Infinity
572
- * ```
573
- */
574
- finite(this: ArgBuilder<C & { readonly argKind: 'number' }>, allow = true): ArgBuilder<C> {
575
- return new ArgBuilder({
576
- ...this.schema,
577
- numberConstraints: { ...this.schema.numberConstraints, finite: allow },
578
- });
579
- }
580
- }
581
-
582
- // --- Factory namespace
583
-
584
- /**
585
- * Arg factory functions — the public API for creating positional arguments.
586
- *
587
- * Each method returns an {@linkcode ArgBuilder} seeded with the correct {@linkcode ArgKind}
588
- * and initial type-level config. Chain modifiers (`.optional()`, `.env()`,
589
- * `.default()`, `.variadic()`, `.stdin()`, `.describe()`, `.deprecated()`) to refine.
590
- *
591
- * All args are **required** by default. Resolution order when extra
592
- * sources are configured: **CLI → stdin → env → default**.
593
- *
594
- * @example Overview — all three kinds with common modifier patterns
595
- * ```ts
596
- * command('process')
597
- * // String arg with env fallback
598
- * .arg('input', arg.string()
599
- * .env('INPUT_FILE')
600
- * .describe('Input file path'))
601
- *
602
- * // Number arg with env + default
603
- * .arg('concurrency', arg.number()
604
- * .env('CONCURRENCY')
605
- * .default(4)
606
- * .describe('Worker threads'))
607
- *
608
- * // Custom arg — hex color parser with env
609
- * .arg('color', arg.custom((raw) => {
610
- * if (!/^#?[0-9a-f]{6}$/i.test(raw)) throw new Error('bad hex');
611
- * return raw.startsWith('#') ? raw : `#${raw}`;
612
- * })
613
- * .env('THEME_COLOR')
614
- * .optional()
615
- * .describe('Theme color (hex)'))
616
- *
617
- * .action(({ args }) => {
618
- * args.input; // string (required)
619
- * args.concurrency; // number (defaulted)
620
- * args.color; // string | undefined (optional custom)
621
- * });
622
- * ```
623
- */
624
- interface ArgFactory {
625
- /**
626
- * String-valued positional argument. Required by default.
627
- *
628
- * @example
629
- * ```ts
630
- * arg.string() // required string
631
- * arg.string().optional() // string | undefined
632
- * arg.string().env('TARGET') // falls back to $TARGET
633
- * arg.string().default('production') // always present
634
- *
635
- * // In a command:
636
- * command('deploy')
637
- * .arg('target', arg.string().env('DEPLOY_TARGET').describe('Deploy target'))
638
- * ```
639
- *
640
- * @returns A required string {@link ArgBuilder}.
641
- */
642
- string(): ArgBuilder<{
643
- readonly valueType: string;
644
- readonly presence: 'required';
645
- readonly variadic: false;
646
- readonly argKind: 'string';
647
- }>;
648
-
649
- /**
650
- * Number-valued positional argument. Required by default.
651
- *
652
- * The parser coerces the raw CLI string to a number and emits a
653
- * `ParseError` if conversion fails. Env values are coerced the same way.
654
- *
655
- * @example
656
- * ```ts
657
- * arg.number() // required number
658
- * arg.number().default(8080) // defaults to 8080
659
- * arg.number().env('PORT') // falls back to $PORT (coerced)
660
- *
661
- * // In a command:
662
- * command('serve')
663
- * .arg('port', arg.number().env('PORT').default(3000).describe('Port'))
664
- * // $ mycli serve 8080 → 8080
665
- * // $ PORT=9090 mycli serve → 9090
666
- * // $ mycli serve → 3000
667
- * ```
668
- *
669
- * Constraints are enforced at the parse and resolution boundaries and also
670
- * compose via chained methods (`.int()`, `.min()`, `.max()`, `.finite()`),
671
- * which override values set here. The resolved value type stays `number`.
672
- *
673
- * @param constraints - Optional numeric constraints. `finite` defaults to
674
- * `true`, so `Infinity` / `-Infinity` are rejected unless `finite: false`.
675
- * @defaultValue `undefined` (finite-only, no bounds, non-integer allowed)
676
- * @returns A required number {@link ArgBuilder}.
677
- */
678
- number(constraints?: NumberConstraints): ArgBuilder<{
679
- readonly valueType: number;
680
- readonly presence: 'required';
681
- readonly variadic: false;
682
- readonly argKind: 'number';
683
- }>;
684
-
685
- /**
686
- * Enum-valued positional argument. Required by default.
687
- *
688
- * Accepts only the listed string literals. The inferred type is the
689
- * union of those literals (e.g. `'us' | 'eu' | 'ap'`), not `string`.
690
- * Invalid values produce a `ParseError` listing allowed options.
691
- *
692
- * @param values - Non-empty tuple of allowed string values.
693
- * @returns A required enum {@link ArgBuilder} typed to the union of `values`.
694
- *
695
- * @example
696
- * ```ts
697
- * arg.enum(['us', 'eu', 'ap']) // required, 'us' | 'eu' | 'ap'
698
- * arg.enum(['dev', 'prod']).default('dev') // defaulted
699
- * arg.enum(['json', 'csv']).optional() // 'json' | 'csv' | undefined
700
- *
701
- * // In a command:
702
- * command('deploy')
703
- * .arg('region', arg.enum(['us', 'eu', 'ap']).env('REGION').describe('Target region'))
704
- * // $ mycli deploy us → 'us'
705
- * // $ mycli deploy invalid → ParseError: Allowed: us, eu, ap
706
- * ```
707
- */
708
- enum<const T extends readonly [string, ...string[]]>(
709
- values: T,
710
- ): ArgBuilder<{
711
- readonly valueType: T[number];
712
- readonly presence: 'required';
713
- readonly variadic: false;
714
- readonly argKind: 'enum';
715
- }>;
716
-
717
- /**
718
- * Custom-parsed positional argument. Required by default.
719
- *
720
- * The parse function receives the raw string and must return a value of
721
- * type `T`. Throw an `Error` (or `ParseError`) to signal invalid input.
722
- * The same parse function is used for both CLI and env values.
723
- *
724
- * @param parseFn - Converts the raw CLI string to `T`.
725
- * @returns A required custom {@link ArgBuilder} typed to the return of `parseFn`.
726
- *
727
- * @example
728
- * ```ts
729
- * arg.custom((raw) => Number.parseInt(raw, 16))
730
- * // inferred type: number
731
- *
732
- * // In a command — parse hex color from CLI or $COLOR:
733
- * command('theme')
734
- * .arg('color', arg.custom((raw) => {
735
- * if (!/^[0-9a-f]{6}$/i.test(raw)) throw new Error('Expected 6-digit hex');
736
- * return `#${raw}`;
737
- * }).env('COLOR').describe('Hex color code'))
738
- * // $ mycli theme ff6600 → '#ff6600'
739
- * // $ COLOR=aabbcc mycli theme → '#aabbcc'
740
- * ```
741
- */
742
- custom<T>(parseFn: ArgParseFn<T>): ArgBuilder<{
743
- readonly valueType: T;
744
- readonly presence: 'required';
745
- readonly variadic: false;
746
- readonly argKind: 'custom';
747
- }>;
748
- }
749
-
750
- /**
751
- * Positional argument schema factory.
752
- *
753
- * Entry point for defining args on a command. Use `arg.<kind>()` to create
754
- * an {@linkcode ArgBuilder}, then chain modifiers and pass the result to
755
- * `command().arg(name, builder)`.
756
- *
757
- * Four kinds are available:
758
- * - `arg.string()` — raw string (most common)
759
- * - `arg.number()` — parsed to number, errors on NaN
760
- * - `arg.enum(values)` — constrained to listed literals
761
- * - `arg.custom(fn)` — arbitrary parse function, infers return type
762
- *
763
- * @example
764
- * ```ts
765
- * import { command, arg } from '@kjanat/dreamcli';
766
- *
767
- * command('deploy')
768
- * .arg('target', arg.string().env('DEPLOY_TARGET').describe('Where to deploy'))
769
- * .arg('port', arg.number().env('PORT').default(3000))
770
- * .action(({ args }) => {
771
- * console.log(`Deploying to ${args.target} on port ${args.port}`);
772
- * });
773
- *
774
- * // $ mycli deploy production 8080 → target='production', port=8080
775
- * // $ DEPLOY_TARGET=staging mycli deploy → target='staging', port=3000
776
- * ```
777
- */
778
- const arg: ArgFactory = {
779
- string(): ArgBuilder<{
780
- readonly valueType: string;
781
- readonly presence: 'required';
782
- readonly variadic: false;
783
- readonly argKind: 'string';
784
- }> {
785
- return new ArgBuilder(createArgSchema('string'));
786
- },
787
-
788
- number(constraints?: NumberConstraints): ArgBuilder<{
789
- readonly valueType: number;
790
- readonly presence: 'required';
791
- readonly variadic: false;
792
- readonly argKind: 'number';
793
- }> {
794
- if (constraints !== undefined) {
795
- assertNumberConstraints(constraints);
796
- }
797
- return new ArgBuilder(
798
- createArgSchema(
799
- 'number',
800
- constraints !== undefined ? { numberConstraints: constraints } : {},
801
- ),
802
- );
803
- },
804
-
805
- enum<const T extends readonly [string, ...string[]]>(
806
- values: T,
807
- ): ArgBuilder<{
808
- readonly valueType: T[number];
809
- readonly presence: 'required';
810
- readonly variadic: false;
811
- readonly argKind: 'enum';
812
- }> {
813
- return new ArgBuilder(createArgSchema('enum', { enumValues: values }));
814
- },
815
-
816
- custom<T>(parseFn: ArgParseFn<T>): ArgBuilder<{
817
- readonly valueType: T;
818
- readonly presence: 'required';
819
- readonly variadic: false;
820
- readonly argKind: 'custom';
821
- }> {
822
- return new ArgBuilder(createArgSchema('custom', { parseFn: parseFn as ArgParseFn<unknown> }));
823
- },
824
- };
825
-
826
- // --- Exports
827
-
828
- export type {
829
- ArgConfig,
830
- ArgFactory,
831
- ArgKind,
832
- ArgParseFn,
833
- ArgPresence,
834
- ArgSchema,
835
- InferArg,
836
- InferArgs,
837
- ResolvedArgValue,
838
- WithArgPresence,
839
- WithVariadic,
840
- };
841
- export { ARG_KINDS, ARG_PRESENCES, ArgBuilder, arg, createArgSchema };