-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbargs.ts
More file actions
1498 lines (1369 loc) · 46.2 KB
/
bargs.ts
File metadata and controls
1498 lines (1369 loc) · 46.2 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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Core bargs API using parser combinator pattern.
*
* Provides `bargs()` for building CLIs with a fluent API, plus combinator
* functions like `pipe()`, `map()`, and `handle()`.
*
* @packageDocumentation
*/
import type {
CamelCaseKeys,
CliBuilder,
Command,
CommandOptions,
CreateOptions,
HandlerFn,
Parser,
ParseResult,
} from './types.js';
import {
generateCompletionScript,
getCompletionCandidates,
validateShell,
} from './completion.js';
import { BargsError, HelpError } from './errors.js';
import { generateCommandHelp, generateHelp } from './help.js';
import { parseSimple } from './parser.js';
import { defaultTheme, getTheme, type Theme } from './theme.js';
import { detectVersionSync } from './version.js';
// ═══════════════════════════════════════════════════════════════════════════════
// UTILITY FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Type guard to check if a value is a thenable (has a `.then` method).
*
* This is more robust than `instanceof Promise` because it catches any
* Promise-like object per the Promises/A+ specification, not just native
* Promises.
*
* @function
* @param value - The value to check
* @returns `true` if the value is thenable
*/
const isThenable = <T>(value: unknown): value is PromiseLike<T> =>
value !== null &&
typeof value === 'object' &&
'then' in value &&
typeof value.then === 'function';
// ═══════════════════════════════════════════════════════════════════════════════
// INTERNAL TYPES
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Transform fn type - can be sync or async.
*
* @group Combinators
* @knipignore
*/
export type TransformFn<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
> = (
result: ParseResult<V1, P1>,
) => ParseResult<V2, P2> | Promise<ParseResult<V2, P2>>;
/** A command entry can be either a leaf command or a nested builder. */
type CommandEntry =
| {
aliases?: string[];
builder: CliBuilder<unknown, readonly unknown[]>;
description?: string;
type: 'nested';
}
| {
aliases?: string[];
cmd: Command<unknown, readonly unknown[]>;
description?: string;
type: 'command';
};
/** Type for commands that may have transforms. */
type CommandWithTransform<V, P extends readonly unknown[]> = Command<V, P> & {
__transform?: (
r: ParseResult<unknown, readonly unknown[]>,
) => ParseResult<V, P>;
};
interface InternalCliState {
/** Alias-to-canonical-name lookup map */
aliasMap: Map<string, string>;
commands: Map<string, CommandEntry>;
defaultCommandName?: string;
globalParser?: Parser<unknown, readonly unknown[]>;
name: string;
options: CreateOptions;
parentGlobals?: ParseResult<unknown, readonly unknown[]>;
theme: Theme;
}
/**
* Parse a command options parameter (string or CommandOptions object).
*
* @function
*/
const parseCommandOptions = (
options: CommandOptions | string | undefined,
): { aliases?: string[]; description?: string } => {
if (options === undefined) {
return {};
}
if (typeof options === 'string') {
return { description: options };
}
return { aliases: options.aliases, description: options.description };
};
/**
* Register command aliases in the alias map.
*
* @function
*/
const registerAliases = (
aliasMap: Map<string, string>,
commands: Map<string, CommandEntry>,
canonicalName: string,
aliases?: string[],
): void => {
if (!aliases) {
return;
}
for (const alias of aliases) {
// Check if alias conflicts with an existing alias
if (aliasMap.has(alias)) {
throw new BargsError(
`Command alias "${alias}" is already registered for command "${aliasMap.get(alias)}"`,
);
}
// Check if alias conflicts with an existing command name
if (commands.has(alias)) {
throw new BargsError(
`Command alias "${alias}" conflicts with existing command name "${alias}"`,
);
}
aliasMap.set(alias, canonicalName);
}
};
/** Async transform type for internal use. */
type AsyncTransform = (
r: ParseResult<unknown, readonly unknown[]>,
) =>
| ParseResult<unknown, readonly unknown[]>
| Promise<ParseResult<unknown, readonly unknown[]>>;
/** Type for parsers that may have transforms. */
type ParserWithTransform<V, P extends readonly unknown[]> = Parser<V, P> & {
__transform?: (
r: ParseResult<unknown, readonly unknown[]>,
) => ParseResult<V, P>;
};
// ═══════════════════════════════════════════════════════════════════════════════
// MERGE COMBINATOR
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Create a command with a handler (terminal in the pipeline).
*
* @group Combinators
*/
export function handle<V, P extends readonly unknown[]>(
fn: HandlerFn<V, P>,
): (parser: Parser<V, P>) => Command<V, P>;
export function handle<V, P extends readonly unknown[]>(
parser: Parser<V, P>,
fn: HandlerFn<V, P>,
): Command<V, P>;
export function handle<V, P extends readonly unknown[]>(
parserOrFn: HandlerFn<V, P> | Parser<V, P>,
maybeFn?: HandlerFn<V, P>,
): ((parser: Parser<V, P>) => Command<V, P>) | Command<V, P> {
// Direct form: handle(parser, fn) returns Command
// Check for Parser first since CallableParser is also a function
if (isParser(parserOrFn)) {
const parser = parserOrFn;
const parserWithTransform = parser as ParserWithTransform<V, P>;
const fn = maybeFn!;
const cmd: CommandWithTransform<V, P> = {
__brand: 'Command',
__optionsSchema: parser.__optionsSchema,
__positionalsSchema: parser.__positionalsSchema,
handler: fn,
};
// Preserve transforms from the parser
if (parserWithTransform.__transform) {
cmd.__transform = parserWithTransform.__transform;
}
return cmd;
}
// Curried form: handle(fn) returns (parser) => Command
const fn = parserOrFn;
return (parser: Parser<V, P>): Command<V, P> => {
const parserWithTransform = parser as ParserWithTransform<V, P>;
const cmd: CommandWithTransform<V, P> = {
__brand: 'Command',
__optionsSchema: parser.__optionsSchema,
__positionalsSchema: parser.__positionalsSchema,
handler: fn,
};
// Preserve transforms from the parser
if (parserWithTransform.__transform) {
cmd.__transform = parserWithTransform.__transform;
}
return cmd;
};
}
/**
* Transform parse result in the pipeline.
*
* @group Combinators
*/
export function map<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
>(fn: TransformFn<V1, P1, V2, P2>): (parser: Parser<V1, P1>) => Parser<V2, P2>;
export function map<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
>(parser: Parser<V1, P1>, fn: TransformFn<V1, P1, V2, P2>): Parser<V2, P2>;
export function map<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
>(
parserOrFn: Parser<V1, P1> | TransformFn<V1, P1, V2, P2>,
maybeFn?: TransformFn<V1, P1, V2, P2>,
): ((parser: Parser<V1, P1>) => Parser<V2, P2>) | Parser<V2, P2> {
// Helper to compose transforms (chains existing + new)
/**
* @function
*/
const composeTransform = (
parser: Parser<V1, P1>,
fn: TransformFn<V1, P1, V2, P2>,
): TransformFn<unknown, readonly unknown[], V2, P2> => {
const existing = (
parser as {
__transform?: (
r: ParseResult<unknown, readonly unknown[]>,
) => ParseResult<V1, P1> | Promise<ParseResult<V1, P1>>;
}
).__transform;
if (!existing) {
return fn as TransformFn<unknown, readonly unknown[], V2, P2>;
}
// Chain: existing transform first, then new transform
return (r: ParseResult<unknown, readonly unknown[]>) => {
const r1 = existing(r);
if (isThenable(r1)) {
return r1.then(fn);
}
return fn(r1);
};
};
// Direct form: map(parser, fn) returns Parser
// Check for Parser first since CallableParser is also a function
if (isParser(parserOrFn)) {
const parser = parserOrFn;
const fn = maybeFn!;
const composedTransform = composeTransform(parser, fn);
return {
...parser,
__brand: 'Parser',
__positionals: [] as unknown as P2,
__transform: composedTransform,
__values: {} as V2,
} as Parser<V2, P2> & { __transform: typeof composedTransform };
}
// Curried form: map(fn) returns (parser) => Parser
const fn = parserOrFn;
return (parser: Parser<V1, P1>): Parser<V2, P2> => {
const composedTransform = composeTransform(parser, fn);
return {
...parser,
__brand: 'Parser',
__positionals: [] as unknown as P2,
__transform: composedTransform,
__values: {} as V2,
} as Parser<V2, P2> & { __transform: typeof composedTransform };
};
}
/**
* Merge multiple parsers into one.
*
* Combines options and positionals from all parsers. Later parsers' options
* override earlier ones if there are conflicts.
*
* @example
*
* ```typescript
* const parser = merge(
* opt.options({ verbose: opt.boolean() }),
* pos.positionals(pos.string({ name: 'file', required: true })),
* );
* ```
*
* @group Combinators
*/
export function merge<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
>(
p1: Parser<V1, P1>,
p2: Parser<V2, P2>,
): Parser<V1 & V2, readonly [...P1, ...P2]>;
export function merge<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
V3,
P3 extends readonly unknown[],
>(
p1: Parser<V1, P1>,
p2: Parser<V2, P2>,
p3: Parser<V3, P3>,
): Parser<V1 & V2 & V3, readonly [...P1, ...P2, ...P3]>;
// ═══════════════════════════════════════════════════════════════════════════════
// MAP COMBINATOR
// ═══════════════════════════════════════════════════════════════════════════════
export function merge<
V1,
P1 extends readonly unknown[],
V2,
P2 extends readonly unknown[],
V3,
P3 extends readonly unknown[],
V4,
P4 extends readonly unknown[],
>(
p1: Parser<V1, P1>,
p2: Parser<V2, P2>,
p3: Parser<V3, P3>,
p4: Parser<V4, P4>,
): Parser<V1 & V2 & V3 & V4, readonly [...P1, ...P2, ...P3, ...P4]>;
export function merge(
...parsers: Array<Parser<unknown, readonly unknown[]>>
): Parser<unknown, readonly unknown[]> {
if (parsers.length === 0) {
throw new BargsError('merge() requires at least one parser');
}
// Start with the first parser and fold the rest in
let result = parsers[0]!;
for (let i = 1; i < parsers.length; i++) {
const next = parsers[i]!;
// Merge options schemas
const mergedOptions = {
...result.__optionsSchema,
...next.__optionsSchema,
};
// Merge positionals schemas
const mergedPositionals = [
...result.__positionalsSchema,
...next.__positionalsSchema,
];
// Preserve transforms from both parsers (chain them)
const resultWithTransform = result as { __transform?: AsyncTransform };
const nextWithTransform = next as { __transform?: AsyncTransform };
let mergedTransform: AsyncTransform | undefined;
if (resultWithTransform.__transform && nextWithTransform.__transform) {
// Chain transforms
const t1 = resultWithTransform.__transform;
const t2 = nextWithTransform.__transform;
mergedTransform = (r) => {
const r1 = t1(r);
if (isThenable(r1)) {
return r1.then(t2);
}
return t2(r1);
};
} else {
mergedTransform =
nextWithTransform.__transform ?? resultWithTransform.__transform;
}
result = {
__brand: 'Parser',
__optionsSchema: mergedOptions,
__positionals: [] as unknown as readonly unknown[],
__positionalsSchema: mergedPositionals,
__values: {} as unknown,
};
if (mergedTransform) {
(result as { __transform?: AsyncTransform }).__transform =
mergedTransform;
}
}
return result;
}
// ═══════════════════════════════════════════════════════════════════════════════
// CAMEL CASE HELPER
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Convert kebab-case string to camelCase.
*
* @function
*/
const kebabToCamel = (s: string): string =>
s.replace(/-([a-zA-Z])/g, (_, c: string) => c.toUpperCase());
/**
* Transform for use with `map()` that converts kebab-case option keys to
* camelCase.
*
* @example
*
* ```typescript
* import { bargs, opt, map, camelCaseValues } from '@boneskull/bargs';
*
* const { values } = await bargs('my-cli')
* .globals(
* map(opt.options({ 'output-dir': opt.string() }), camelCaseValues),
* )
* .parseAsync();
*
* console.log(values.outputDir); // camelCased!
* ```
*
* @function
* @group Transforms
*/
export const camelCaseValues = <V, P extends readonly unknown[]>(
result: ParseResult<V, P>,
): ParseResult<CamelCaseKeys<V>, P> => ({
...result,
values: Object.fromEntries(
Object.entries(result.values as Record<string, unknown>).map(([k, v]) => [
kebabToCamel(k),
v,
]),
) as CamelCaseKeys<V>,
});
// ═══════════════════════════════════════════════════════════════════════════════
// CLI BUILDER
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Create a new CLI.
*
* @example
*
* ```typescript
* const cli = await bargs('my-app', { version: '1.0.0' })
* .globals(
* map(opt.options({ verbose: opt.boolean() }), ({ values }) => ({
* values: { ...values, ts: Date.now() },
* positionals: [] as const,
* })),
* )
* .command(
* 'greet',
* pos.positionals(pos.string({ name: 'name', required: true })),
* ({ positionals }) => console.log(`Hello, ${positionals[0]}!`),
* )
* .parseAsync();
* ```
*
* @function
* @group Core API
*/
export const bargs = (
name: string,
options: CreateOptions = {},
): CliBuilder<Record<string, never>, readonly []> => {
const theme = options.theme ? getTheme(options.theme) : defaultTheme;
return createCliBuilder<Record<string, never>, readonly []>({
aliasMap: new Map(),
commands: new Map(),
name,
options,
theme,
});
};
/**
* Check if something is a Command (has __brand: 'Command').
*
* @function
*/
const isCommand = (x: unknown): x is Command<unknown, readonly unknown[]> => {
if (x === null || x === undefined) {
return false;
}
const obj = x as Record<string, unknown>;
return '__brand' in obj && obj.__brand === 'Command';
};
// Internal type for CliBuilder with internal methods
type InternalCliBuilder<V, P extends readonly unknown[]> = CliBuilder<V, P> & {
__getState: () => InternalCliState;
__parseWithParentGlobals: (
args: string[],
parentGlobals: ParseResult<unknown, readonly unknown[]>,
allowAsync: boolean,
) =>
| (ParseResult<V, P> & { command?: string })
| Promise<ParseResult<V, P> & { command?: string }>;
};
/**
* Create a CLI builder.
*
* @function
*/
const createCliBuilder = <V, P extends readonly unknown[]>(
state: InternalCliState,
): CliBuilder<V, P> => {
const builder: InternalCliBuilder<V, P> = {
// Internal method for completion support - not part of public API
__getState(): InternalCliState {
return state;
},
// Internal method for nested command support - not part of public API
// Handles HelpError here so nested builders can render their own help
__parseWithParentGlobals(
args: string[],
parentGlobals: ParseResult<unknown, readonly unknown[]>,
allowAsync: boolean,
):
| (ParseResult<V, P> & { command?: string })
| Promise<ParseResult<V, P> & { command?: string }> {
const stateWithGlobals = { ...state, parentGlobals };
try {
const result = parseCore(stateWithGlobals, args, allowAsync);
if (isThenable(result)) {
return result.catch((error: unknown) => {
if (error instanceof HelpError) {
handleHelpError(error, stateWithGlobals); // exits process
}
throw error;
}) as Promise<ParseResult<V, P> & { command?: string }>;
}
return result as ParseResult<V, P> & { command?: string };
} catch (error) {
if (error instanceof HelpError) {
handleHelpError(error, stateWithGlobals); // exits process
}
throw error;
}
},
// Overloaded command(): accepts (name, factory, options?),
// (name, Command, options?), or (name, Parser, handler, options?)
command<CV, CP extends readonly unknown[]>(
name: string,
cmdOrParserOrFactory:
| ((builder: CliBuilder<V, P>) => CliBuilder<CV, CP>)
| Command<CV, CP>
| Parser<CV, CP>,
handlerOrDescOrOpts?: CommandOptions | HandlerFn<CV & V, CP> | string,
maybeDescOrOpts?: CommandOptions | string,
): CliBuilder<V, P> {
// Form 3: command(name, factory, options?) - factory for nested commands with parent globals
// Check this FIRST before isParser since that checks for __brand which a plain function won't have
if (
typeof cmdOrParserOrFactory === 'function' &&
!isParser(cmdOrParserOrFactory) &&
!isCommand(cmdOrParserOrFactory)
) {
const factory = cmdOrParserOrFactory as (
b: CliBuilder<V, P>,
) => CliBuilder<CV, CP>;
const { aliases, description } = parseCommandOptions(
handlerOrDescOrOpts as CommandOptions | string | undefined,
);
// Create a child builder with parent global TYPES (for type inference)
// but NOT the globalParser (parent globals are passed via parentGlobals at runtime,
// not re-parsed from args)
const childBuilder = createCliBuilder<V, P>({
aliasMap: new Map(),
commands: new Map(),
globalParser: undefined, // Parent globals come via parentGlobals, not re-parsing
name,
options: state.options,
theme: state.theme,
});
// Call factory to let user add commands
const nestedBuilder = factory(childBuilder);
state.commands.set(name, {
aliases,
builder: nestedBuilder as CliBuilder<unknown, readonly unknown[]>,
description,
type: 'nested',
});
registerAliases(state.aliasMap, state.commands, name, aliases);
return this;
}
let cmd: Command<unknown, readonly unknown[]>;
let aliases: string[] | undefined;
let description: string | undefined;
if (isCommand(cmdOrParserOrFactory)) {
// Form 1: command(name, Command, options?)
cmd = cmdOrParserOrFactory;
const opts = parseCommandOptions(
handlerOrDescOrOpts as CommandOptions | string | undefined,
);
aliases = opts.aliases;
description = opts.description;
} else if (isParser(cmdOrParserOrFactory)) {
// Form 2: command(name, Parser, handler, options?)
const parser = cmdOrParserOrFactory;
const handler = handlerOrDescOrOpts as HandlerFn<CV & V, CP>;
const opts = parseCommandOptions(maybeDescOrOpts);
aliases = opts.aliases;
description = opts.description;
// Create Command from Parser + handler
const parserWithTransform = parser as ParserWithTransform<CV, CP>;
const newCmd: CommandWithTransform<CV & V, CP> = {
__brand: 'Command',
__optionsSchema: parser.__optionsSchema,
__positionalsSchema: parser.__positionalsSchema,
handler,
};
// Preserve transforms from the parser
if (parserWithTransform.__transform) {
newCmd.__transform = parserWithTransform.__transform as (
r: ParseResult<unknown, readonly unknown[]>,
) => ParseResult<CV & V, CP>;
}
cmd = newCmd as Command<unknown, readonly unknown[]>;
} else {
/* c8 ignore next 3 -- unreachable with TypeScript */
throw new Error(
'command() requires a Command, Parser, CliBuilder, or factory function as second argument',
);
}
state.commands.set(name, { aliases, cmd, description, type: 'command' });
registerAliases(state.aliasMap, state.commands, name, aliases);
return this;
},
// Overloaded defaultCommand(): accepts name, Command, or (Parser, handler)
defaultCommand<CV, CP extends readonly unknown[]>(
nameOrCmdOrParser: Command<CV, CP> | Parser<CV, CP> | string,
maybeHandler?: HandlerFn<CV & V, CP>,
): CliBuilder<V, P> {
// Form 1: defaultCommand(name) - just set the name
if (typeof nameOrCmdOrParser === 'string') {
return createCliBuilder<V, P>({
...state,
defaultCommandName: nameOrCmdOrParser,
});
}
// Generate a unique name for the default command
const defaultName = '__default__';
if (isCommand(nameOrCmdOrParser)) {
// Form 2: defaultCommand(Command)
state.commands.set(defaultName, {
cmd: nameOrCmdOrParser,
description: undefined,
type: 'command',
});
} else if (isParser(nameOrCmdOrParser)) {
// Form 3: defaultCommand(Parser, handler)
const parser = nameOrCmdOrParser;
const handler = maybeHandler!;
const parserWithTransform = parser as ParserWithTransform<CV, CP>;
const newCmd: CommandWithTransform<CV & V, CP> = {
__brand: 'Command',
__optionsSchema: parser.__optionsSchema,
__positionalsSchema: parser.__positionalsSchema,
handler,
};
// Preserve transforms from the parser
if (parserWithTransform.__transform) {
newCmd.__transform = parserWithTransform.__transform as (
r: ParseResult<unknown, readonly unknown[]>,
) => ParseResult<CV & V, CP>;
}
state.commands.set(defaultName, {
cmd: newCmd as Command<unknown, readonly unknown[]>,
description: undefined,
type: 'command',
});
} else {
/* c8 ignore next 2 -- unreachable with TypeScript */
throw new Error('defaultCommand() requires a name, Command, or Parser');
}
return createCliBuilder<V, P>({
...state,
defaultCommandName: defaultName,
});
},
globals<V2, P2 extends readonly unknown[]>(
parser: Parser<V2, P2>,
): CliBuilder<V & V2, readonly [...P, ...P2]> {
// Merge with existing global parser if present
let mergedParser: Parser<unknown, readonly unknown[]>;
if (state.globalParser) {
// Merge option schemas
const mergedOptions = {
...state.globalParser.__optionsSchema,
...parser.__optionsSchema,
};
// Merge positional schemas
const mergedPositionals = [
...state.globalParser.__positionalsSchema,
...parser.__positionalsSchema,
];
mergedParser = {
__brand: 'Parser',
__optionsSchema: mergedOptions,
__positionals: [] as unknown as readonly unknown[],
__positionalsSchema: mergedPositionals,
__values: {} as unknown,
};
} else {
mergedParser = parser as Parser<unknown, readonly unknown[]>;
}
return createCliBuilder<V & V2, readonly [...P, ...P2]>({
...state,
globalParser: mergedParser,
});
},
parse(
args: string[] = process.argv.slice(2),
): ParseResult<V, P> & { command?: string } {
try {
const result = parseCore(state, args, false);
if (isThenable(result)) {
throw new BargsError(
'Async transform or handler detected. Use parseAsync() instead of parse().',
);
}
return result as ParseResult<V, P> & { command?: string };
} catch (error) {
if (error instanceof HelpError) {
handleHelpError(error, state); // exits process, never returns
}
throw error;
}
},
async parseAsync(
args: string[] = process.argv.slice(2),
): Promise<ParseResult<V, P> & { command?: string }> {
try {
return (await parseCore(state, args, true)) as ParseResult<V, P> & {
command?: string;
};
} catch (error) {
if (error instanceof HelpError) {
handleHelpError(error, state); // exits process, never returns
}
throw error;
}
},
};
// Return as public CliBuilder (hiding internal method from type)
return builder as CliBuilder<V, P>;
};
/**
* Core parse logic shared between parse() and parseAsync().
*
* @function
*/
const parseCore = (
state: InternalCliState,
args: string[],
allowAsync: boolean,
):
| (ParseResult<unknown, readonly unknown[]> & { command?: string })
| Promise<
ParseResult<unknown, readonly unknown[]> & { command?: string }
> => {
const { aliasMap, commands, options, theme } = state;
/**
* Terminates the process for early-exit scenarios (--help, --version,
* --completion-script). This is standard CLI behavior - users expect these
* flags to print output and exit immediately.
*
* @remarks
* The return statement exists only to satisfy TypeScript. In practice,
* `process.exit()` terminates the process and this function never returns.
* @function
*/
const exitProcess = (exitCode: number): never => {
process.exit(exitCode);
};
// Handle --help
if (args.includes('--help') || args.includes('-h')) {
// Check for command-specific help
const helpIndex = args.findIndex((a) => a === '--help' || a === '-h');
const commandIndex = args.findIndex((a) => !a.startsWith('-'));
if (commandIndex >= 0 && commandIndex < helpIndex && commands.size > 0) {
const rawCommandName = args[commandIndex]!;
// Resolve alias to canonical name if needed
const commandName = aliasMap.get(rawCommandName) ?? rawCommandName;
const commandEntry = commands.get(commandName);
if (commandEntry) {
// For nested commands, check if there are more args to delegate
if (commandEntry.type === 'nested') {
// Get args after the command name (e.g., ['list', '--help'] from ['history', 'list', '--help'])
const nestedArgs = args.slice(commandIndex + 1);
// If there are more args (subcommand or --help), delegate to nested builder
if (nestedArgs.length > 0) {
// Delegate to nested builder's help handling
const internalNestedBuilder =
commandEntry.builder as InternalCliBuilder<
unknown,
readonly unknown[]
>;
// Create a minimal parent globals result for help generation
const emptyGlobals: ParseResult<unknown, readonly unknown[]> = {
positionals: [],
values: {},
};
// This will trigger the nested builder's help handling
return internalNestedBuilder.__parseWithParentGlobals(
nestedArgs,
emptyGlobals,
true,
);
}
// If no more args, show help for this nested command group
return showNestedCommandHelp(state, commandName);
}
// Regular command help
console.log(generateCommandHelpNew(state, commandName, theme));
return exitProcess(0);
}
}
console.log(generateHelpNew(state, theme));
return exitProcess(0);
}
// Handle --version
if (args.includes('--version')) {
const version = detectVersionSync(options.version);
if (version) {
console.log(version);
} else {
console.log('Version information not available');
}
return exitProcess(0);
}
// Handle shell completion (when enabled)
if (options.completion) {
// Handle --completion-script <shell>
const completionScriptIndex = args.indexOf('--completion-script');
if (completionScriptIndex >= 0) {
const shellArg = args[completionScriptIndex + 1];
if (!shellArg) {
console.error(
'Error: --completion-script requires a shell argument (bash, zsh, or fish)',
);
return exitProcess(1);
}
try {
const shell = validateShell(shellArg);
console.log(generateCompletionScript(state.name, shell));
return exitProcess(0);
} catch (err) {
console.error(`Error: ${(err as Error).message}`);
return exitProcess(1);
}
}
// Handle --get-bargs-completions <shell> <...words>
const getCompletionsIndex = args.indexOf('--get-bargs-completions');
if (getCompletionsIndex >= 0) {
const shellArg = args[getCompletionsIndex + 1];
if (!shellArg) {
// No shell specified, output nothing
return exitProcess(0);
}
try {
const shell = validateShell(shellArg);
// Words are everything after the shell argument
const words = args.slice(getCompletionsIndex + 2);
const candidates = getCompletionCandidates(state, shell, words);
if (candidates.length > 0) {
console.log(candidates.join('\n'));
}
return exitProcess(0);
} catch {
// Invalid shell, output nothing
return exitProcess(0);
}
}
}
// If we have commands, dispatch to the appropriate one
if (commands.size > 0) {
return runWithCommands(state, args, allowAsync);
}
// Simple CLI (no commands)
return runSimple(state, args, allowAsync);
};
/**
* Show help for a nested command group by delegating to the nested builder.
* This function always terminates the process (either via the nested builder's
* help handling or via error exit).
*
* @function
*/
const showNestedCommandHelp = (
state: InternalCliState,
commandName: string,
): never => {
const commandEntry = state.commands.get(commandName);
if (!commandEntry || commandEntry.type !== 'nested') {
console.error(`Unknown command group: ${commandName}`);
process.exit(1);
}
// Delegate to nested builder with --help - this will exit the process
const internalNestedBuilder = commandEntry.builder as InternalCliBuilder<
unknown,
readonly unknown[]
>;
const emptyGlobals: ParseResult<unknown, readonly unknown[]> = {
positionals: [],
values: {},
};
// This will show the nested builder's help and exit the process.
// The void operator explicitly marks this as intentionally unhandled since
// process.exit() inside will terminate before the promise resolves.
void internalNestedBuilder.__parseWithParentGlobals(
['--help'],
emptyGlobals,
true,
);
// This should never be reached since help handling calls process.exit()