-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.ts
More file actions
726 lines (673 loc) · 20.7 KB
/
types.ts
File metadata and controls
726 lines (673 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/**
* TypeScript type definitions for the bargs CLI argument parser.
*
* Defines all public interfaces and types including:
*
* - Option definitions (`StringOption`, `BooleanOption`, `EnumOption`, etc.)
* - Positional definitions (`StringPositional`, `VariadicPositional`, etc.)
* - Schema types (`OptionsSchema`, `PositionalsSchema`)
* - Type inference utilities (`InferOptions`, `InferPositionals`)
* - Parser combinator types (`Parser`, `Command`, `ParseResult`)
*
* @packageDocumentation
*/
import type { ThemeInput } from './theme.js';
// ═══════════════════════════════════════════════════════════════════════════════
// OPTION DEFINITIONS
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Array option definition (--flag value --flag value2).
*
* @group Option Types
*/
export interface ArrayOption extends OptionBase {
default?: number[] | string[];
/** Element type of the array (for primitive arrays) */
items?: 'number' | 'string';
type: 'array';
}
/**
* Boolean option definition.
*
* @group Option Types
*/
export interface BooleanOption extends OptionBase {
default?: boolean;
type: 'boolean';
}
/**
* Transform all keys of an object type from kebab-case to camelCase.
*
* Used with `camelCaseValues` to provide type-safe camelCase option keys.
*
* @example
*
* ```typescript
* type Original = { 'output-dir': string; 'dry-run': boolean };
* type Camel = CamelCaseKeys<Original>; // { outputDir: string; dryRun: boolean }
* ```
*
* @group Type Utilities
*/
export type CamelCaseKeys<T> = {
[K in keyof T as KebabToCamel<K & string>]: T[K];
};
/**
* CLI builder for fluent configuration.
*
* @group Parser Types
*/
export interface CliBuilder<
TGlobalValues = Record<string, never>,
TGlobalPositionals extends readonly unknown[] = readonly [],
> {
/**
* Register a command with a Command object.
*
* Note: When using this form, the handler only sees command-local types. Use
* the (parser, handler) form for merged global+command types.
*/
command<CV, CP extends readonly unknown[]>(
name: string,
cmd: Command<CV, CP>,
options?: CommandOptions | string,
): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Register a command with a Parser and handler separately.
*
* This form provides full type inference for merged global + command types.
* The handler receives `TGlobalValues & CV` for values.
*/
command<CV, CP extends readonly unknown[]>(
name: string,
parser: Parser<CV, CP>,
handler: HandlerFn<CV & TGlobalValues, CP>,
options?: CommandOptions | string,
): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Register a nested command group using a factory function.
*
* This form provides full type inference - the factory receives a builder
* that already has parent globals typed, so all nested command handlers see
* the merged types.
*
* @example
*
* ```typescript
* bargs('main')
* .globals(opt.options({ verbose: opt.boolean() }))
* .command(
* 'remote',
* (remote) =>
* remote.command('add', addParser, ({ values }) => {
* // values.verbose is typed correctly!
* }),
* 'Manage remotes',
* );
* ```
*/
command<CV, CP extends readonly unknown[]>(
name: string,
factory: (
builder: CliBuilder<TGlobalValues, TGlobalPositionals>,
) => CliBuilder<CV, CP>,
options?: CommandOptions | string,
): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Set the default command by name (must be registered first).
*/
defaultCommand(name: string): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Set the default command with a Command object.
*
* Note: When using this form, the handler only sees command-local types. Use
* the (parser, handler) form for merged global+command types.
*/
defaultCommand<CV, CP extends readonly unknown[]>(
cmd: Command<CV, CP>,
): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Set the default command with a Parser and handler separately.
*
* This form provides full type inference for merged global + command types.
* The handler receives `TGlobalValues & CV` for values.
*/
defaultCommand<CV, CP extends readonly unknown[]>(
parser: Parser<CV, CP>,
handler: HandlerFn<CV & TGlobalValues, CP>,
): CliBuilder<TGlobalValues, TGlobalPositionals>;
/**
* Set or extend global options/transforms that apply to all commands.
*
* When called on a builder that already has globals (e.g., from a factory),
* the new globals are merged with existing ones.
*/
globals<V, P extends readonly unknown[]>(
parser: Parser<V, P>,
): CliBuilder<TGlobalValues & V, readonly [...TGlobalPositionals, ...P]>;
/**
* Parse arguments synchronously and run handlers.
*
* Throws if any transform or handler returns a Promise.
*
* @remarks
* Early exit scenarios (`--help`, `--version`, `--completion-script`, or
* invalid/missing commands) will call `process.exit()` and never return. This
* is standard CLI behavior.
*/
parse(args?: string[]): ParseResult<TGlobalValues, TGlobalPositionals> & {
command?: string;
};
/**
* Parse arguments asynchronously and run handlers.
*
* Supports async transforms and handlers.
*
* @remarks
* Early exit scenarios (`--help`, `--version`, `--completion-script`, or
* invalid/missing commands) will call `process.exit()` and never return. This
* is standard CLI behavior.
*/
parseAsync(args?: string[]): Promise<
ParseResult<TGlobalValues, TGlobalPositionals> & {
command?: string;
}
>;
}
/**
* Result from CLI execution (extends ParseResult with command name).
*
* @group Parser Types
*/
export interface CliResult<
TValues = Record<string, unknown>,
TPositionals extends readonly unknown[] = readonly unknown[],
> extends ParseResult<TValues, TPositionals> {
/** The command that was executed, if any */
command?: string;
}
/**
* Command with handler attached (terminal in the pipeline).
*
* @group Parser Types
*/
export interface Command<
TValues = Record<string, unknown>,
TPositionals extends readonly unknown[] = readonly unknown[],
> {
/** Brand for type discrimination. Do not use directly. */
readonly __brand: 'Command';
/** Options schema. Do not use directly. */
readonly __optionsSchema: OptionsSchema;
/** Positionals schema. Do not use directly. */
readonly __positionalsSchema: PositionalsSchema;
/** Command description for help text */
readonly description?: string;
/** The handler function */
readonly handler: HandlerFn<TValues, TPositionals>;
}
/**
* Registered command definition.
*
* @group Parser Types
*/
export interface CommandDef<
TValues = Record<string, unknown>,
TPositionals extends readonly unknown[] = readonly unknown[],
> {
/** The command */
readonly command: Command<TValues, TPositionals>;
/** Description for help */
readonly description?: string;
/** Command name */
readonly name: string;
}
/**
* Options for command registration.
*
* Used as an alternative to a simple string description when registering
* commands, allowing additional configuration like aliases.
*
* @example
*
* ```typescript
* .command('add', addParser, handler, {
* description: 'Add a new item',
* aliases: ['a', 'new']
* })
* ```
*
* @group Parser Types
*/
export interface CommandOptions {
/**
* Alternative names for this command.
*
* @example
*
* ```typescript
* { "aliases": ["co", "sw"] } // 'checkout' can be invoked as 'co' or 'sw'
* ```
*/
aliases?: string[];
/** Command description displayed in help text */
description?: string;
}
/**
* Count option definition (--verbose --verbose = 2).
*
* @group Option Types
*/
export interface CountOption extends OptionBase {
default?: number;
type: 'count';
}
/**
* Options for bargs().
*
* @group Core API
*/
export interface CreateOptions {
/**
* Enable shell completion support.
*
* When `true`, the CLI will respond to:
*
* - `--completion-script <shell>` - Output shell completion script
* - `--get-bargs-completions <shell> <...words>` - Return completion candidates
*
* Supported shells: bash, zsh, fish
*
* @example
*
* ```typescript
* bargs('mytool', { completion: true })
* .command('build', ...)
* .parseAsync();
*
* // Then run: mytool --completion-script bash >> ~/.bashrc
* ```
*/
completion?: boolean;
/** Description shown in help */
description?: string;
/** Epilog text shown after help output */
epilog?: false | string;
/** Color theme for help output */
theme?: ThemeInput;
/** Version string (enables --version flag) */
version?: string;
}
/**
* Enum array option definition (--flag a --flag b with limited choices).
*
* @group Option Types
*/
export interface EnumArrayOption<T extends string = string> extends OptionBase {
/** Valid choices for array elements */
choices: readonly T[];
default?: T[];
type: 'array';
}
// ═══════════════════════════════════════════════════════════════════════════════
// POSITIONAL DEFINITIONS
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Enum option definition with string choices.
*
* @group Option Types
*/
export interface EnumOption<T extends string = string> extends OptionBase {
choices: readonly T[];
default?: T;
type: 'enum';
}
/**
* Enum positional definition with string choices.
*
* @group Positional Types
*/
export interface EnumPositional<
T extends string = string,
> extends PositionalBase {
choices: readonly T[];
default?: T;
type: 'enum';
}
/**
* Handler function signature.
*
* @group Parser Types
*/
export type HandlerFn<TValues, TPositionals extends readonly unknown[]> = (
result: ParseResult<TValues, TPositionals>,
) => Promise<void> | void;
/**
* Infer the TypeScript type from an option definition.
*
* @group Type Utilities
*/
export type InferOption<T extends OptionDef> = T extends BooleanOption
? T['required'] extends true
? boolean
: T['default'] extends boolean
? boolean
: boolean | undefined
: T extends NumberOption
? T['required'] extends true
? number
: T['default'] extends number
? number
: number | undefined
: T extends StringOption
? T['required'] extends true
? string
: T['default'] extends string
? string
: string | undefined
: T extends EnumOption<infer E>
? T['required'] extends true
? E
: T['default'] extends E
? E
: E | undefined
: T extends EnumArrayOption<infer E>
? E[]
: T extends ArrayOption
? T['items'] extends 'number'
? number[]
: string[]
: T extends CountOption
? number
: never;
// ═══════════════════════════════════════════════════════════════════════════════
// CAMELCASE UTILITIES
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Infer values type from an options schema.
*
* @group Type Utilities
*/
export type InferOptions<T extends OptionsSchema> = {
[K in keyof T]: InferOption<T[K]>;
};
/**
* Infer a single positional's type.
*
* @group Type Utilities
*/
export type InferPositional<T extends PositionalDef> =
T extends NumberPositional
? T['required'] extends true
? number
: T['default'] extends number
? number
: number | undefined
: T extends StringPositional
? T['required'] extends true
? string
: T['default'] extends string
? string
: string | undefined
: T extends EnumPositional<infer E>
? T['required'] extends true
? E
: T['default'] extends E
? E
: E | undefined
: T extends VariadicPositional
? T['items'] extends 'number'
? number[]
: string[]
: never;
/**
* Recursively build a tuple type from a positionals schema array.
*
* @group Type Utilities
*/
export type InferPositionals<T extends PositionalsSchema> = T extends readonly [
infer First,
...infer Rest,
]
? First extends PositionalDef
? Rest extends PositionalsSchema
? readonly [InferPositional<First>, ...InferPositionals<Rest>]
: readonly [InferPositional<First>]
: readonly []
: T extends readonly [infer Only]
? Only extends PositionalDef
? readonly [InferPositional<Only>]
: readonly []
: T extends readonly []
? readonly []
: readonly InferPositional<T[number]>[];
/**
* Infer the output positionals type from a transforms config.
*
* @group Type Utilities
*/
export type InferTransformedPositionals<
TPositionalsIn extends readonly unknown[],
TTransforms,
> = TTransforms extends { positionals: PositionalsTransformFn<any, infer TOut> }
? TOut extends readonly unknown[]
? TOut
: TPositionalsIn
: TPositionalsIn;
/**
* Infer the output values type from a transforms config.
*
* @group Type Utilities
*/
export type InferTransformedValues<TValuesIn, TTransforms> =
TTransforms extends { values: ValuesTransformFn<any, infer TOut> }
? TOut
: TValuesIn;
// ═══════════════════════════════════════════════════════════════════════════════
// TYPE INFERENCE
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Convert a kebab-case string type to camelCase.
*
* @example
*
* ```typescript
* type Result = KebabToCamel<'output-dir'>; // 'outputDir'
* type Nested = KebabToCamel<'my-long-option'>; // 'myLongOption'
* ```
*
* @group Type Utilities
*/
export type KebabToCamel<S extends string> = S extends `${infer T}-${infer U}`
? `${T}${Capitalize<KebabToCamel<U>>}`
: S;
/**
* Number option definition.
*
* @group Option Types
*/
export interface NumberOption extends OptionBase {
default?: number;
type: 'number';
}
/**
* Number positional.
*
* @group Positional Types
*/
export interface NumberPositional extends PositionalBase {
default?: number;
type: 'number';
}
/**
* Union of all option definitions.
*
* @group Option Types
*/
export type OptionDef =
| ArrayOption
| BooleanOption
| CountOption
| EnumArrayOption<string>
| EnumOption<string>
| NumberOption
| StringOption;
// ═══════════════════════════════════════════════════════════════════════════════
// TRANSFORMS
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Options schema: a record of option names to their definitions.
*
* @group Option Types
*/
export type OptionsSchema = Record<string, OptionDef>;
/**
* Parser represents accumulated parse state with options and positionals
* schemas. This is a branded type for type-level tracking.
*
* @group Parser Types
*/
export interface Parser<
TValues = Record<string, unknown>,
TPositionals extends readonly unknown[] = readonly unknown[],
> {
/** Brand for type discrimination. Do not use directly. */
readonly __brand: 'Parser';
/** Options schema. Do not use directly. */
readonly __optionsSchema: OptionsSchema;
/** Phantom type for positionals. Do not use directly. */
readonly __positionals: TPositionals;
/** Positionals schema. Do not use directly. */
readonly __positionalsSchema: PositionalsSchema;
/** Phantom type for values. Do not use directly. */
readonly __values: TValues;
}
/**
* Core parse result shape flowing through the pipeline.
*
* @group Parser Types
*/
export interface ParseResult<
TValues = Record<string, unknown>,
TPositionals extends readonly unknown[] = readonly unknown[],
> {
positionals: TPositionals;
values: TValues;
}
/**
* Union of positional definitions.
*
* @group Positional Types
*/
export type PositionalDef =
| EnumPositional<string>
| NumberPositional
| StringPositional
| VariadicPositional;
/**
* Positionals can be a tuple (ordered) or a single variadic.
*
* @group Positional Types
*/
export type PositionalsSchema = readonly PositionalDef[];
// ═══════════════════════════════════════════════════════════════════════════════
// PARSER COMBINATOR TYPES
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Positionals transform function.
*
* @group Parser Types
*/
export type PositionalsTransformFn<
TIn extends readonly unknown[],
TOut extends readonly unknown[],
> = (positionals: TIn) => Promise<TOut> | TOut;
/**
* String option definition.
*
* @group Option Types
*/
export interface StringOption extends OptionBase {
default?: string;
type: 'string';
}
/**
* String positional.
*
* @group Positional Types
*/
export interface StringPositional extends PositionalBase {
default?: string;
type: 'string';
}
/**
* Transforms configuration for modifying parsed results.
*
* @group Parser Types
*/
export interface TransformsConfig<
TValuesIn,
TValuesOut,
TPositionalsIn extends readonly unknown[],
TPositionalsOut extends readonly unknown[],
> {
/** Transform parsed positionals tuple */
positionals?: PositionalsTransformFn<TPositionalsIn, TPositionalsOut>;
/** Transform parsed option values */
values?: ValuesTransformFn<TValuesIn, TValuesOut>;
}
/**
* Values transform function.
*
* @group Parser Types
*/
export type ValuesTransformFn<TIn, TOut> = (
values: TIn,
) => Promise<TOut> | TOut;
// ═══════════════════════════════════════════════════════════════════════════════
// CLI BUILDER TYPES
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Variadic positional (rest args).
*
* @group Positional Types
*/
export interface VariadicPositional extends PositionalBase {
items: 'number' | 'string';
type: 'variadic';
}
/**
* Base properties shared by all option definitions.
*/
interface OptionBase {
/**
* Short or long aliases for this option.
*
* - Single-character aliases (e.g., `'v'`) become short flags (`-v`)
* - Multi-character aliases (e.g., `'verb'`) become long flags (`--verb`)
*
* @example
*
* ```typescript
* opt.boolean({ aliases: ['v', 'verb'] }); // -v, --verb, --verbose
* ```
*/
aliases?: string[];
/** Option description displayed in help text */
description?: string;
/** Group name for help text organization */
group?: string;
/** Whether this option is hidden from help */
hidden?: boolean;
/** Whether this option is required */
required?: boolean;
}
/**
* Base properties for positional definitions.
*/
interface PositionalBase {
description?: string;
/** Display name for help text (defaults to arg0, arg1, etc.) */
name?: string;
required?: boolean;
}