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