index.d.ts (41377B)
1 2 type TrimRight<S extends string> = S extends `${infer R} ` ? TrimRight<R> : S; 3 type TrimLeft<S extends string> = S extends ` ${infer R}` ? TrimLeft<R> : S; 4 type Trim<S extends string> = TrimLeft<TrimRight<S>>; 5 6 type CamelCase<S extends string> = S extends `${infer W}-${infer Rest}` 7 ? CamelCase<`${W}${Capitalize<Rest>}`> 8 : S; 9 10 // This is a trick to encourage TypeScript to resolve intersections for displaying, 11 // like { a: number } & { b : string } => { a: number, b: string } 12 // References: 13 // - https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts 14 // - https://effectivetypescript.com/2022/02/25/gentips-4-display/ 15 type Resolve<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; 16 17 // This is a trick to encourage editor to suggest the known literals while still 18 // allowing any BaseType value. 19 // References: 20 // - https://github.com/microsoft/TypeScript/issues/29729 21 // - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts 22 // - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts 23 type LiteralUnion<LiteralType, BaseType extends string | number> = LiteralType | (BaseType & Record<never, never>); 24 25 // Side note: not trying to represent arrays as non-empty, keep it simple. 26 // https://stackoverflow.com/a/56006703/1082434 27 type InferVariadic<S extends string, ArgT> = 28 S extends `${string}...` 29 ? ArgT[] 30 : ArgT; 31 32 type InferArgumentType<Value extends string, DefaultT, CoerceT, ChoicesT> = 33 [CoerceT] extends [undefined] 34 ? InferVariadic<Value, [ChoicesT] extends [undefined] ? string : ChoicesT> | DefaultT 35 : ([ChoicesT] extends [undefined] 36 ? CoerceT | DefaultT 37 : CoerceT | DefaultT | ChoicesT 38 ) 39 40 41 // Special handling for optional variadic argument, won't be undefined as implementation returns []. 42 type InferArgumentOptionalType<Value extends string, DefaultT, CoerceT, ChoicesT> = 43 Value extends `${string}...` 44 ? InferArgumentType<Value, [DefaultT] extends [undefined] ? never : DefaultT, CoerceT, ChoicesT> 45 : InferArgumentType<Value, DefaultT, CoerceT, ChoicesT> 46 47 // ArgRequired comes from .argRequired()/.argOptional(), and ArgRequiredFromUsage is implied by usage <required>/[optional] 48 type ResolveRequired<ArgRequired extends boolean|undefined, ArgRequiredFromUsage extends boolean> = 49 ArgRequired extends undefined 50 ? ArgRequiredFromUsage 51 : ArgRequired; 52 53 type InferArgumentTypeResolvedRequired<Value extends string, DefaultT, CoerceT, ArgRequired extends boolean, ChoicesT> = 54 ArgRequired extends true 55 ? InferArgumentType<Value, never, CoerceT, ChoicesT> 56 : InferArgumentOptionalType<Value, DefaultT, CoerceT, ChoicesT>; 57 58 // Resolve whether argument required, and strip []/<> from around value. 59 type InferArgument<S extends string, DefaultT = undefined, CoerceT = undefined, ArgRequired extends boolean|undefined = undefined, ChoicesT = undefined> = 60 S extends `<${infer Value}>` 61 ? InferArgumentTypeResolvedRequired<Value, DefaultT, CoerceT, ResolveRequired<ArgRequired, true>, ChoicesT> 62 : S extends `[${infer Value}]` 63 ? InferArgumentTypeResolvedRequired<Value, DefaultT, CoerceT, ResolveRequired<ArgRequired, false>, ChoicesT> 64 : InferArgumentTypeResolvedRequired<S, DefaultT, CoerceT, ResolveRequired<ArgRequired, true>, ChoicesT>; // the implementation fallback is treat as <required> 65 66 type InferArguments<S extends string> = 67 S extends `${infer First} ${infer Rest}` 68 ? [InferArgument<First>, ...InferArguments<TrimLeft<Rest>>] 69 : [InferArgument<S>]; 70 71 type InferCommmandArguments<S extends string> = 72 S extends `${string} ${infer Args}` 73 ? InferArguments<TrimLeft<Args>> 74 : []; 75 76 type FlagsToFlag<Flags extends string> = 77 Flags extends `${string},${infer LongFlag}` 78 ? TrimLeft<LongFlag> 79 : Flags extends `${string}|${infer LongFlag}` 80 ? TrimLeft<LongFlag> 81 : Flags extends `${string} ${infer LongFlag}` 82 ? TrimLeft<LongFlag> 83 : Flags; 84 85 type ConvertFlagToName<Flag extends string> = 86 Flag extends `--no-${infer Name}` 87 ? CamelCase<Name> 88 : Flag extends `--${infer Name}` 89 ? CamelCase<Name> 90 : Flag extends `-${infer Name}` 91 ? CamelCase<Name> 92 : never; 93 94 type CombineOptions<Options, O> = 95 keyof O extends keyof Options 96 ? { [K in keyof Options]: K extends keyof O ? Options[K] | O[keyof O] : Options[K] } 97 : Options & O; 98 99 type IsAlwaysDefined<DefaulT, Mandatory extends boolean> = 100 Mandatory extends true 101 ? true 102 : [undefined] extends [DefaulT] 103 ? false 104 : true; 105 106 // Modify PresetT to take into account negated. 107 type NegatePresetType<Flag extends string, PresetT> = 108 Flag extends `--no-${string}` 109 ? undefined extends PresetT ? false : PresetT 110 : undefined extends PresetT ? true : PresetT; 111 112 // Modify DefaultT to take into account negated. 113 type NegateDefaultType<Flag extends string, DefaultT> = 114 Flag extends `--no-${string}` 115 ? [undefined] extends [DefaultT] ? true : DefaultT 116 : [undefined] extends [DefaultT] ? never : DefaultT; // don't add undefined, will make property optional later 117 118 // Modify ValueT to take into account coerce function. 119 type CoerceValueType<CoerceT, ValueT> = 120 [ValueT] extends [never] 121 ? never 122 : [CoerceT] extends [undefined] 123 ? ValueT 124 : CoerceT; 125 126 // Modify PresetT to take into account coerce function. 127 type CoercePresetType<CoerceT, PresetT> = 128 [PresetT] extends [never] 129 ? never 130 : [CoerceT] extends [undefined] 131 ? PresetT 132 : undefined extends PresetT ? undefined : CoerceT; 133 134 type BuildOptionProperty<Name extends string, FullValueT, AlwaysDefined extends boolean> = 135 AlwaysDefined extends true 136 ? { [K in Name]: FullValueT } 137 : { [K in Name]?: FullValueT }; 138 139 type InferOptionsCombine<Options, Name extends string, FullValueT, AlwaysDefined extends boolean> = 140 Resolve<CombineOptions<Options, BuildOptionProperty<Name, FullValueT, AlwaysDefined>>>; 141 142 // Combine the possible types 143 type InferOptionsNegateCombo<Options, Flag extends string, Name extends string, ValueT, PresetT, DefaultT, AlwaysDefined extends boolean> = 144 Flag extends `--no-${string}` 145 ? Name extends keyof Options 146 ? InferOptionsCombine<Options, Name, PresetT, true> // combo does not set default, leave that to positive option 147 : InferOptionsCombine<Options, Name, PresetT | DefaultT, true> // lone negated option sets default 148 : InferOptionsCombine<Options, Name, ValueT | PresetT | DefaultT, AlwaysDefined>; 149 150 // Recalc values taking into account negated option. 151 // Fill in appropriate PresetT value if undefined. 152 type InferOptionTypes<Options, Flag extends string, Value extends string, ValueT, PresetT, DefaultT, CoerceT, Mandatory extends boolean, ChoicesT> = 153 InferOptionsNegateCombo<Options, Flag, ConvertFlagToName<Flag>, 154 CoerceValueType<CoerceT, [ChoicesT] extends [undefined] ? InferVariadic<Value, ValueT> : InferVariadic<Value, ChoicesT>>, 155 NegatePresetType<Flag, CoercePresetType<CoerceT, PresetT>>, 156 NegateDefaultType<Flag, DefaultT>, 157 IsAlwaysDefined<DefaultT, Mandatory>>; 158 159 type InferOptionsFlag<Options, Flags extends string, Value extends string, ValueT, PresetT, DefaultT, CoerceT, Mandatory extends boolean, ChoicesT> = 160 InferOptionTypes<Options, FlagsToFlag<Trim<Flags>>, Trim<Value>, ValueT, PresetT, DefaultT, CoerceT, Mandatory, ChoicesT>; 161 162 // Split up Usage into Flags and Value 163 type InferOptions<Options, Usage extends string, DefaultT, CoerceT, Mandatory extends boolean, PresetT = undefined, ChoicesT = undefined> = 164 Usage extends `${infer Flags} <${infer Value}>` 165 ? InferOptionsFlag<Options, Flags, Value, string, never, DefaultT, CoerceT, Mandatory, ChoicesT> 166 : Usage extends `${infer Flags} [${infer Value}]` 167 ? InferOptionsFlag<Options, Flags, Value, string, PresetT, DefaultT, CoerceT, Mandatory, ChoicesT> 168 : InferOptionsFlag<Options, Usage, '', never, PresetT, DefaultT, CoerceT, Mandatory, ChoicesT>; 169 170 export type CommandUnknownOpts = Command<unknown[], OptionValues>; 171 172 // ----- full copy of normal commander typings from here down, with extra type inference ----- 173 174 // Using method rather than property for method-signature-style, to document method overloads separately. Allow either. 175 /* eslint-disable @typescript-eslint/method-signature-style */ 176 /* eslint-disable @typescript-eslint/no-explicit-any */ 177 178 export class CommanderError extends Error { 179 code: string; 180 exitCode: number; 181 message: string; 182 nestedError?: string; 183 184 /** 185 * Constructs the CommanderError class 186 * @param exitCode - suggested exit code which could be used with process.exit 187 * @param code - an id string representing the error 188 * @param message - human-readable description of the error 189 * @constructor 190 */ 191 constructor(exitCode: number, code: string, message: string); 192 } 193 194 export class InvalidArgumentError extends CommanderError { 195 /** 196 * Constructs the InvalidArgumentError class 197 * @param message - explanation of why argument is invalid 198 * @constructor 199 */ 200 constructor(message: string); 201 } 202 export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name 203 204 export interface ErrorOptions { // optional parameter for error() 205 /** an id string representing the error */ 206 code?: string; 207 /** suggested exit code which could be used with process.exit */ 208 exitCode?: number; 209 } 210 211 export class Argument<Usage extends string = '', DefaultT = undefined, CoerceT = undefined, ArgRequired extends boolean|undefined = undefined, ChoicesT = undefined> { 212 description: string; 213 required: boolean; 214 variadic: boolean; 215 defaultValue?: any; 216 defaultValueDescription?: string; 217 argChoices?: string[]; 218 219 /** 220 * Initialize a new command argument with the given name and description. 221 * The default is that the argument is required, and you can explicitly 222 * indicate this with <> around the name. Put [] around the name for an optional argument. 223 */ 224 constructor(arg: Usage, description?: string); 225 226 /** 227 * Return argument name. 228 */ 229 name(): string; 230 231 /** 232 * Set the default value, and optionally supply the description to be displayed in the help. 233 */ 234 default<T>(value: T, description?: string): Argument<Usage, T, CoerceT, ArgRequired, ChoicesT>; 235 236 /** 237 * Set the custom handler for processing CLI command arguments into argument values. 238 */ 239 argParser<T>(fn: (value: string, previous: T) => T): Argument<Usage, DefaultT, T, ArgRequired, undefined>; // setting ChoicesT to undefined because argParser overwrites choices 240 241 /** 242 * Only allow argument value to be one of choices. 243 */ 244 choices<T extends readonly string[]>(values: T): Argument<Usage, DefaultT, undefined, ArgRequired, T[number]>; // setting CoerceT to undefined because choices overrides argParser 245 246 /** 247 * Make argument required. 248 */ 249 argRequired(): Argument<Usage, DefaultT, CoerceT, true, ChoicesT>; 250 251 /** 252 * Make argument optional. 253 */ 254 argOptional(): Argument<Usage, DefaultT, CoerceT, false, ChoicesT>; 255 } 256 257 export class Option<Usage extends string = '', PresetT = undefined, DefaultT = undefined, CoerceT = undefined, Mandatory extends boolean = false, ChoicesT = undefined> { 258 flags: string; 259 description: string; 260 261 required: boolean; // A value must be supplied when the option is specified. 262 optional: boolean; // A value is optional when the option is specified. 263 variadic: boolean; 264 mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. 265 short?: string; 266 long?: string; 267 negate: boolean; 268 defaultValue?: any; 269 defaultValueDescription?: string; 270 presetArg?: unknown; 271 envVar?: string; 272 parseArg?: <T>(value: string, previous: T) => T; 273 hidden: boolean; 274 argChoices?: string[]; 275 276 constructor(flags: Usage, description?: string); 277 278 /** 279 * Set the default value, and optionally supply the description to be displayed in the help. 280 */ 281 default<T>(value: T, description?: string): Option<Usage, PresetT, T, CoerceT, Mandatory, ChoicesT>; 282 283 /** 284 * Preset to use when option used without option-argument, especially optional but also boolean and negated. 285 * The custom processing (parseArg) is called. 286 * 287 * @example 288 * ```ts 289 * new Option('--color').default('GREYSCALE').preset('RGB'); 290 * new Option('--donate [amount]').preset('20').argParser(parseFloat); 291 * ``` 292 */ 293 preset<T>(arg: T): Option<Usage, T, DefaultT, CoerceT, Mandatory, ChoicesT>; 294 295 /** 296 * Add option name(s) that conflict with this option. 297 * An error will be displayed if conflicting options are found during parsing. 298 * 299 * @example 300 * ```ts 301 * new Option('--rgb').conflicts('cmyk'); 302 * new Option('--js').conflicts(['ts', 'jsx']); 303 * ``` 304 */ 305 conflicts(names: string | string[]): this; 306 307 /** 308 * Specify implied option values for when this option is set and the implied options are not. 309 * 310 * The custom processing (parseArg) is not called on the implied values. 311 * 312 * @example 313 * program 314 * .addOption(new Option('--log', 'write logging information to file')) 315 * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); 316 */ 317 implies(optionValues: OptionValues): this; 318 319 /** 320 * Set environment variable to check for option value. 321 * 322 * An environment variables is only used if when processed the current option value is 323 * undefined, or the source of the current value is 'default' or 'config' or 'env'. 324 */ 325 env(name: string): this; 326 327 /** 328 * Calculate the full description, including defaultValue etc. 329 */ 330 fullDescription(): string; 331 332 /** 333 * Set the custom handler for processing CLI option arguments into option values. 334 */ 335 argParser<T>(fn: (value: string, previous: T) => T): Option<Usage, PresetT, DefaultT, T, Mandatory, undefined>; // setting ChoicesT to undefined because argParser overrides choices 336 337 /** 338 * Whether the option is mandatory and must have a value after parsing. 339 */ 340 makeOptionMandatory<M extends boolean = true>(mandatory?: M): Option<Usage, PresetT, DefaultT, CoerceT, M, ChoicesT>; 341 342 /** 343 * Hide option in help. 344 */ 345 hideHelp(hide?: boolean): this; 346 347 /** 348 * Only allow option value to be one of choices. 349 */ 350 choices<T extends readonly string[]>(values: T): Option<Usage, PresetT, DefaultT, undefined, Mandatory, T[number]>; // setting CoerceT to undefined becuase choices overrides argParser 351 352 /** 353 * Return option name. 354 */ 355 name(): string; 356 357 /** 358 * Return option name, in a camelcase format that can be used 359 * as a object attribute key. 360 */ 361 attributeName(): string; 362 363 /** 364 * Return whether a boolean option. 365 * 366 * Options are one of boolean, negated, required argument, or optional argument. 367 */ 368 isBoolean(): boolean; 369 } 370 371 export class Help { 372 /** output helpWidth, long lines are wrapped to fit */ 373 helpWidth?: number; 374 sortSubcommands: boolean; 375 sortOptions: boolean; 376 showGlobalOptions: boolean; 377 378 constructor(); 379 380 /** Get the command term to show in the list of subcommands. */ 381 subcommandTerm(cmd: CommandUnknownOpts): string; 382 /** Get the command summary to show in the list of subcommands. */ 383 subcommandDescription(cmd: CommandUnknownOpts): string; 384 /** Get the option term to show in the list of options. */ 385 optionTerm(option: Option): string; 386 /** Get the option description to show in the list of options. */ 387 optionDescription(option: Option): string; 388 /** Get the argument term to show in the list of arguments. */ 389 argumentTerm(argument: Argument): string; 390 /** Get the argument description to show in the list of arguments. */ 391 argumentDescription(argument: Argument): string; 392 393 /** Get the command usage to be displayed at the top of the built-in help. */ 394 commandUsage(cmd: CommandUnknownOpts): string; 395 /** Get the description for the command. */ 396 commandDescription(cmd: CommandUnknownOpts): string; 397 398 /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */ 399 visibleCommands(cmd: CommandUnknownOpts): CommandUnknownOpts[]; 400 /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */ 401 visibleOptions(cmd: CommandUnknownOpts): Option[]; 402 /** Get an array of the visible global options. (Not including help.) */ 403 visibleGlobalOptions(cmd: CommandUnknownOpts): Option[]; 404 /** Get an array of the arguments which have descriptions. */ 405 visibleArguments(cmd: CommandUnknownOpts): Argument[]; 406 407 /** Get the longest command term length. */ 408 longestSubcommandTermLength(cmd: CommandUnknownOpts, helper: Help): number; 409 /** Get the longest option term length. */ 410 longestOptionTermLength(cmd: CommandUnknownOpts, helper: Help): number; 411 /** Get the longest global option term length. */ 412 longestGlobalOptionTermLength(cmd: CommandUnknownOpts, helper: Help): number; 413 /** Get the longest argument term length. */ 414 longestArgumentTermLength(cmd: CommandUnknownOpts, helper: Help): number; 415 /** Calculate the pad width from the maximum term length. */ 416 padWidth(cmd: CommandUnknownOpts, helper: Help): number; 417 418 /** 419 * Wrap the given string to width characters per line, with lines after the first indented. 420 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. 421 */ 422 wrap(str: string, width: number, indent: number, minColumnWidth?: number): string; 423 424 /** Generate the built-in help text. */ 425 formatHelp(cmd: CommandUnknownOpts, helper: Help): string; 426 } 427 export type HelpConfiguration = Partial<Help>; 428 429 export interface ParseOptions { 430 from: 'node' | 'electron' | 'user'; 431 } 432 export interface HelpContext { // optional parameter for .help() and .outputHelp() 433 error: boolean; 434 } 435 export interface AddHelpTextContext { // passed to text function used with .addHelpText() 436 error: boolean; 437 command: Command; 438 } 439 export interface OutputConfiguration { 440 writeOut?(str: string): void; 441 writeErr?(str: string): void; 442 getOutHelpWidth?(): number; 443 getErrHelpWidth?(): number; 444 outputError?(str: string, write: (str: string) => void): void; 445 446 } 447 448 export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll'; 449 export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction'; 450 // The source is a string so author can define their own too. 451 export type OptionValueSource = LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string> | undefined; 452 453 export type OptionValues = Record<string, unknown>; 454 455 export class Command<Args extends any[] = [], Opts extends OptionValues = {}> { 456 args: string[]; 457 processedArgs: Args; 458 readonly commands: readonly CommandUnknownOpts[]; 459 readonly options: readonly Option[]; 460 readonly registeredArguments: readonly Argument[]; 461 parent: CommandUnknownOpts | null; 462 463 constructor(name?: string); 464 465 /** 466 * Set the program version to `str`. 467 * 468 * This method auto-registers the "-V, --version" flag 469 * which will print the version number when passed. 470 * 471 * You can optionally supply the flags and description to override the defaults. 472 */ 473 version(str: string, flags?: string, description?: string): this; 474 /** 475 * Get the program version. 476 */ 477 version(): string | undefined; 478 /** 479 * Define a command, implemented using an action handler. 480 * 481 * @remarks 482 * The command description is supplied using `.description`, not as a parameter to `.command`. 483 * 484 * @example 485 * ```ts 486 * program 487 * .command('clone <source> [destination]') 488 * .description('clone a repository into a newly created directory') 489 * .action((source, destination) => { 490 * console.log('clone command called'); 491 * }); 492 * ``` 493 * 494 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` 495 * @param opts - configuration options 496 * @returns new command 497 */ 498 command<Usage extends string>(nameAndArgs: Usage, opts?: CommandOptions): Command<[...InferCommmandArguments<Usage>]>; 499 /** 500 * Define a command, implemented in a separate executable file. 501 * 502 * @remarks 503 * The command description is supplied as the second parameter to `.command`. 504 * 505 * @example 506 * ```ts 507 * program 508 * .command('start <service>', 'start named service') 509 * .command('stop [service]', 'stop named service, or all if no name supplied'); 510 * ``` 511 * 512 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` 513 * @param description - description of executable command 514 * @param opts - configuration options 515 * @returns `this` command for chaining 516 */ 517 command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this; 518 519 /** 520 * Factory routine to create a new unattached command. 521 * 522 * See .command() for creating an attached subcommand, which uses this routine to 523 * create the command. You can override createCommand to customise subcommands. 524 */ 525 createCommand(name?: string): Command; 526 527 /** 528 * Add a prepared subcommand. 529 * 530 * See .command() for creating an attached subcommand which inherits settings from its parent. 531 * 532 * @returns `this` command for chaining 533 */ 534 addCommand(cmd: CommandUnknownOpts, opts?: CommandOptions): this; 535 536 /** 537 * Factory routine to create a new unattached argument. 538 * 539 * See .argument() for creating an attached argument, which uses this routine to 540 * create the argument. You can override createArgument to return a custom argument. 541 */ 542 createArgument<Usage extends string>(name: Usage, description?: string): Argument<Usage>; 543 544 /** 545 * Define argument syntax for command. 546 * 547 * The default is that the argument is required, and you can explicitly 548 * indicate this with <> around the name. Put [] around the name for an optional argument. 549 * 550 * @example 551 * ``` 552 * program.argument('<input-file>'); 553 * program.argument('[output-file]'); 554 * ``` 555 * 556 * @returns `this` command for chaining 557 */ 558 argument<S extends string, T>( 559 flags: S, description: string, fn: (value: string, previous: T) => T): Command<[...Args, InferArgument<S, undefined, T>], Opts>; 560 argument<S extends string, T>( 561 flags: S, description: string, fn: (value: string, previous: T) => T, defaultValue: T): Command<[...Args, InferArgument<S, T, T>], Opts>; 562 argument<S extends string>( 563 usage: S, description?: string): Command<[...Args, InferArgument<S, undefined>], Opts>; 564 argument<S extends string, DefaultT>( 565 usage: S, description: string, defaultValue: DefaultT): Command<[...Args, InferArgument<S, DefaultT>], Opts>; 566 567 /** 568 * Define argument syntax for command, adding a prepared argument. 569 * 570 * @returns `this` command for chaining 571 */ 572 addArgument<Usage extends string, DefaultT, CoerceT, ArgRequired extends boolean|undefined, ChoicesT>( 573 arg: Argument<Usage, DefaultT, CoerceT, ArgRequired, ChoicesT>): Command<[...Args, InferArgument<Usage, DefaultT, CoerceT, ArgRequired, ChoicesT>], Opts>; 574 575 576 /** 577 * Define argument syntax for command, adding multiple at once (without descriptions). 578 * 579 * See also .argument(). 580 * 581 * @example 582 * ``` 583 * program.arguments('<cmd> [env]'); 584 * ``` 585 * 586 * @returns `this` command for chaining 587 */ 588 arguments<Names extends string>(args: Names): Command<[...Args, ...InferArguments<Names>], Opts>; 589 590 591 /** 592 * Override default decision whether to add implicit help command. 593 * 594 * @example 595 * ``` 596 * addHelpCommand() // force on 597 * addHelpCommand(false); // force off 598 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details 599 * ``` 600 * 601 * @returns `this` command for chaining 602 */ 603 addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this; 604 605 /** 606 * Add hook for life cycle event. 607 */ 608 hook(event: HookEvent, listener: (thisCommand: this, actionCommand: CommandUnknownOpts) => void | Promise<void>): this; 609 610 /** 611 * Register callback to use as replacement for calling process.exit. 612 */ 613 exitOverride(callback?: (err: CommanderError) => never | void): this; 614 615 /** 616 * Display error message and exit (or call exitOverride). 617 */ 618 error(message: string, errorOptions?: ErrorOptions): never; 619 620 /** 621 * You can customise the help with a subclass of Help by overriding createHelp, 622 * or by overriding Help properties using configureHelp(). 623 */ 624 createHelp(): Help; 625 626 /** 627 * You can customise the help by overriding Help properties using configureHelp(), 628 * or with a subclass of Help by overriding createHelp(). 629 */ 630 configureHelp(configuration: HelpConfiguration): this; 631 /** Get configuration */ 632 configureHelp(): HelpConfiguration; 633 634 /** 635 * The default output goes to stdout and stderr. You can customise this for special 636 * applications. You can also customise the display of errors by overriding outputError. 637 * 638 * The configuration properties are all functions: 639 * ``` 640 * // functions to change where being written, stdout and stderr 641 * writeOut(str) 642 * writeErr(str) 643 * // matching functions to specify width for wrapping help 644 * getOutHelpWidth() 645 * getErrHelpWidth() 646 * // functions based on what is being written out 647 * outputError(str, write) // used for displaying errors, and not used for displaying help 648 * ``` 649 */ 650 configureOutput(configuration: OutputConfiguration): this; 651 /** Get configuration */ 652 configureOutput(): OutputConfiguration; 653 654 /** 655 * Copy settings that are useful to have in common across root command and subcommands. 656 * 657 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) 658 */ 659 copyInheritedSettings(sourceCommand: CommandUnknownOpts): this; 660 661 /** 662 * Display the help or a custom message after an error occurs. 663 */ 664 showHelpAfterError(displayHelp?: boolean | string): this; 665 666 /** 667 * Display suggestion of similar commands for unknown commands, or options for unknown options. 668 */ 669 showSuggestionAfterError(displaySuggestion?: boolean): this; 670 671 /** 672 * Register callback `fn` for the command. 673 * 674 * @example 675 * ``` 676 * program 677 * .command('serve') 678 * .description('start service') 679 * .action(function() { 680 * // do work here 681 * }); 682 * ``` 683 * 684 * @returns `this` command for chaining 685 */ 686 action(fn: (...args: [...Args, Opts, this]) => void | Promise<void>): this; 687 688 /** 689 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. 690 * 691 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required 692 * option-argument is indicated by `<>` and an optional option-argument by `[]`. 693 * 694 * See the README for more details, and see also addOption() and requiredOption(). 695 * 696 * @example 697 * 698 * ```js 699 * program 700 * .option('-p, --pepper', 'add pepper') 701 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument 702 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default 703 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function 704 * ``` 705 * 706 * @returns `this` command for chaining 707 */ 708 option<S extends string>( 709 usage: S, description?: string): Command<Args, InferOptions<Opts, S, undefined, undefined, false>>; 710 option<S extends string, DefaultT extends string | boolean | string[] | []>( 711 usage: S, description?: string, defaultValue?: DefaultT): Command<Args, InferOptions<Opts, S, DefaultT, undefined, false>>; 712 option<S extends string, T>( 713 usage: S, description: string, parseArg: (value: string, previous: T) => T): Command<Args, InferOptions<Opts, S, undefined, T, false>>; 714 option<S extends string, T>( 715 usage: S, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): Command<Args, InferOptions<Opts, S, T, T, false>>; 716 717 /** 718 * Define a required option, which must have a value after parsing. This usually means 719 * the option must be specified on the command line. (Otherwise the same as .option().) 720 * 721 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. 722 */ 723 requiredOption<S extends string>( 724 usage: S, description?: string): Command<Args, InferOptions<Opts, S, undefined, undefined, true>>; 725 requiredOption<S extends string, DefaultT extends string | boolean | string[]>( 726 usage: S, description?: string, defaultValue?: DefaultT): Command<Args, InferOptions<Opts, S, DefaultT, undefined, true>>; 727 requiredOption<S extends string, T>( 728 usage: S, description: string, parseArg: (value: string, previous: T) => T): Command<Args, InferOptions<Opts, S, undefined, T, true>>; 729 requiredOption<S extends string, T, D extends T>( 730 usage: S, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: D): Command<Args, InferOptions<Opts, S, D, T, true>>; 731 732 /** 733 * Factory routine to create a new unattached option. 734 * 735 * See .option() for creating an attached option, which uses this routine to 736 * create the option. You can override createOption to return a custom option. 737 */ 738 739 createOption<Usage extends string>(flags: Usage, description?: string): Option<Usage>; 740 741 /** 742 * Add a prepared Option. 743 * 744 * See .option() and .requiredOption() for creating and attaching an option in a single call. 745 */ 746 addOption<Usage extends string, PresetT, DefaultT, CoerceT, Mandatory extends boolean, ChoicesT>( 747 option: Option<Usage, PresetT, DefaultT, CoerceT, Mandatory, ChoicesT>): Command<Args, InferOptions<Opts, Usage, DefaultT, CoerceT, Mandatory, PresetT, ChoicesT>>; 748 749 /** 750 * Whether to store option values as properties on command object, 751 * or store separately (specify false). In both cases the option values can be accessed using .opts(). 752 * 753 * @returns `this` command for chaining 754 */ 755 storeOptionsAsProperties<T extends OptionValues>(): this & T; 756 storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T; 757 storeOptionsAsProperties(storeAsProperties?: boolean): this; 758 759 /** 760 * Retrieve option value. 761 */ 762 getOptionValue<K extends keyof Opts>(key: K): Opts[K]; 763 getOptionValue(key: string): unknown; 764 765 /** 766 * Store option value. 767 */ 768 setOptionValue<K extends keyof Opts>(key: K, value: unknown): this; 769 setOptionValue(key: string, value: unknown): this; 770 771 /** 772 * Store option value and where the value came from. 773 */ 774 setOptionValueWithSource<K extends keyof Opts>(key: K, value: unknown, source: OptionValueSource): this; 775 setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this; 776 777 /** 778 * Get source of option value. 779 */ 780 getOptionValueSource<K extends keyof Opts>(key: K): OptionValueSource | undefined; 781 getOptionValueSource(key: string): OptionValueSource | undefined; 782 783 /** 784 * Get source of option value. See also .optsWithGlobals(). 785 */ 786 getOptionValueSourceWithGlobals<K extends keyof Opts>(key: K): OptionValueSource | undefined; 787 getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined; 788 789 /** 790 * Alter parsing of short flags with optional values. 791 * 792 * @example 793 * ``` 794 * // for `.option('-f,--flag [value]'): 795 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour 796 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` 797 * ``` 798 * 799 * @returns `this` command for chaining 800 */ 801 combineFlagAndOptionalValue(combine?: boolean): this; 802 803 /** 804 * Allow unknown options on the command line. 805 * 806 * @returns `this` command for chaining 807 */ 808 allowUnknownOption(allowUnknown?: boolean): this; 809 810 /** 811 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. 812 * 813 * @returns `this` command for chaining 814 */ 815 allowExcessArguments(allowExcess?: boolean): this; 816 817 /** 818 * Enable positional options. Positional means global options are specified before subcommands which lets 819 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. 820 * 821 * The default behaviour is non-positional and global options may appear anywhere on the command line. 822 * 823 * @returns `this` command for chaining 824 */ 825 enablePositionalOptions(positional?: boolean): this; 826 827 /** 828 * Pass through options that come after command-arguments rather than treat them as command-options, 829 * so actual command-options come before command-arguments. Turning this on for a subcommand requires 830 * positional options to have been enabled on the program (parent commands). 831 * 832 * The default behaviour is non-positional and options may appear before or after command-arguments. 833 * 834 * @returns `this` command for chaining 835 */ 836 passThroughOptions(passThrough?: boolean): this; 837 838 /** 839 * Parse `argv`, setting options and invoking commands when defined. 840 * 841 * The default expectation is that the arguments are from node and have the application as argv[0] 842 * and the script being run in argv[1], with user parameters after that. 843 * 844 * @example 845 * ``` 846 * program.parse(process.argv); 847 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions 848 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] 849 * ``` 850 * 851 * @returns `this` command for chaining 852 */ 853 parse(argv?: readonly string[], options?: ParseOptions): this; 854 855 /** 856 * Parse `argv`, setting options and invoking commands when defined. 857 * 858 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. 859 * 860 * The default expectation is that the arguments are from node and have the application as argv[0] 861 * and the script being run in argv[1], with user parameters after that. 862 * 863 * @example 864 * ``` 865 * program.parseAsync(process.argv); 866 * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions 867 * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] 868 * ``` 869 * 870 * @returns Promise 871 */ 872 parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>; 873 874 /** 875 * Parse options from `argv` removing known options, 876 * and return argv split into operands and unknown arguments. 877 * 878 * argv => operands, unknown 879 * --known kkk op => [op], [] 880 * op --known kkk => [op], [] 881 * sub --unknown uuu op => [sub], [--unknown uuu op] 882 * sub -- --unknown uuu op => [sub --unknown uuu op], [] 883 */ 884 parseOptions(argv: string[]): ParseOptionsResult; 885 886 /** 887 * Return an object containing local option values as key-value pairs 888 */ 889 opts(): Opts; 890 891 /** 892 * Return an object containing merged local and global option values as key-value pairs. 893 */ 894 optsWithGlobals<T extends OptionValues>(): T; 895 896 /** 897 * Set the description. 898 * 899 * @returns `this` command for chaining 900 */ 901 902 description(str: string): this; 903 /** @deprecated since v8, instead use .argument to add command argument with description */ 904 description(str: string, argsDescription: Record<string, string>): this; 905 /** 906 * Get the description. 907 */ 908 description(): string; 909 910 /** 911 * Set the summary. Used when listed as subcommand of parent. 912 * 913 * @returns `this` command for chaining 914 */ 915 916 summary(str: string): this; 917 /** 918 * Get the summary. 919 */ 920 summary(): string; 921 922 /** 923 * Set an alias for the command. 924 * 925 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. 926 * 927 * @returns `this` command for chaining 928 */ 929 alias(alias: string): this; 930 /** 931 * Get alias for the command. 932 */ 933 alias(): string; 934 935 /** 936 * Set aliases for the command. 937 * 938 * Only the first alias is shown in the auto-generated help. 939 * 940 * @returns `this` command for chaining 941 */ 942 aliases(aliases: readonly string[]): this; 943 /** 944 * Get aliases for the command. 945 */ 946 aliases(): string[]; 947 948 /** 949 * Set the command usage. 950 * 951 * @returns `this` command for chaining 952 */ 953 usage(str: string): this; 954 /** 955 * Get the command usage. 956 */ 957 usage(): string; 958 959 /** 960 * Set the name of the command. 961 * 962 * @returns `this` command for chaining 963 */ 964 name(str: string): this; 965 /** 966 * Get the name of the command. 967 */ 968 name(): string; 969 970 /** 971 * Set the name of the command from script filename, such as process.argv[1], 972 * or require.main.filename, or __filename. 973 * 974 * (Used internally and public although not documented in README.) 975 * 976 * @example 977 * ```ts 978 * program.nameFromFilename(require.main.filename); 979 * ``` 980 * 981 * @returns `this` command for chaining 982 */ 983 nameFromFilename(filename: string): this; 984 985 /** 986 * Set the directory for searching for executable subcommands of this command. 987 * 988 * @example 989 * ```ts 990 * program.executableDir(__dirname); 991 * // or 992 * program.executableDir('subcommands'); 993 * ``` 994 * 995 * @returns `this` command for chaining 996 */ 997 executableDir(path: string): this; 998 /** 999 * Get the executable search directory. 1000 */ 1001 executableDir(): string | null; 1002 1003 /** 1004 * Output help information for this command. 1005 * 1006 * Outputs built-in help, and custom text added using `.addHelpText()`. 1007 * 1008 */ 1009 outputHelp(context?: HelpContext): void; 1010 /** @deprecated since v7 */ 1011 outputHelp(cb?: (str: string) => string): void; 1012 1013 /** 1014 * Return command help documentation. 1015 */ 1016 helpInformation(context?: HelpContext): string; 1017 1018 /** 1019 * You can pass in flags and a description to override the help 1020 * flags and help description for your command. Pass in false 1021 * to disable the built-in help option. 1022 */ 1023 helpOption(flags?: string | boolean, description?: string): this; 1024 1025 /** 1026 * Output help information and exit. 1027 * 1028 * Outputs built-in help, and custom text added using `.addHelpText()`. 1029 */ 1030 help(context?: HelpContext): never; 1031 /** @deprecated since v7 */ 1032 help(cb?: (str: string) => string): never; 1033 1034 /** 1035 * Add additional text to be displayed with the built-in help. 1036 * 1037 * Position is 'before' or 'after' to affect just this command, 1038 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. 1039 */ 1040 addHelpText(position: AddHelpTextPosition, text: string): this; 1041 addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this; 1042 1043 /** 1044 * Add a listener (callback) for when events occur. (Implemented using EventEmitter.) 1045 */ 1046 on(event: string | symbol, listener: (...args: any[]) => void): this; 1047 } 1048 1049 export interface CommandOptions { 1050 hidden?: boolean; 1051 isDefault?: boolean; 1052 /** @deprecated since v7, replaced by hidden */ 1053 noHelp?: boolean; 1054 } 1055 export interface ExecutableCommandOptions extends CommandOptions { 1056 executableFile?: string; 1057 } 1058 1059 export interface ParseOptionsResult { 1060 operands: string[]; 1061 unknown: string[]; 1062 } 1063 1064 export function createCommand(name?: string): Command; 1065 export function createOption<Usage extends string>(flags: Usage, description?: string): Option<Usage>; 1066 export function createArgument<Usage extends string>(name: Usage, description?: string): Argument<Usage>; 1067 1068 export const program: Command; 1069