UNPKG

48.9 kBTypeScriptView Raw
1// Type definitions for yargs 17.0
2// Project: https://github.com/chevex/yargs, https://yargs.js.org
3// Definitions by: Martin Poelstra <https://github.com/poelstra>
4// Mizunashi Mana <https://github.com/mizunashi-mana>
5// Jeffery Grajkowski <https://github.com/pushplay>
6// Jimi (Dimitris) Charalampidis <https://github.com/JimiC>
7// Steffen Viken Valvåg <https://github.com/steffenvv>
8// Emily Marigold Klassen <https://github.com/forivall>
9// ExE Boss <https://github.com/ExE-Boss>
10// Aankhen <https://github.com/Aankhen>
11// Ben Coe <https://github.com/bcoe>
12// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
13// TypeScript Version: 3.0
14
15// The following TSLint rules have been disabled:
16// unified-signatures: Because there is useful information in the argument names of the overloaded signatures
17
18// Convention:
19// Use 'union types' when:
20// - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>')
21// - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys'])
22// An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters
23// have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter
24// has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`,
25// thus it's preferred to use `command: string | ReadonlyArray<string>`
26// Use parameterless declaration instead of declaring all parameters optional,
27// when all parameters are optional and more than one
28
29import { DetailedArguments, Configuration } from 'yargs-parser';
30
31declare namespace yargs {
32 type BuilderCallback<T, R> = ((args: Argv<T>) => PromiseLike<Argv<R>>) | ((args: Argv<T>) => Argv<R>) | ((args: Argv<T>) => void);
33
34 type ParserConfigurationOptions = Configuration & {
35 /** Sort commands alphabetically. Default is `false` */
36 'sort-commands': boolean;
37 };
38
39 /**
40 * The type parameter `T` is the expected shape of the parsed options.
41 * `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling
42 * back to `unknown` for unknown options.
43 *
44 * For the return type / `argv` property, we create a mapped type over
45 * `Arguments<T>` to simplify the inferred type signature in client code.
46 */
47 interface Argv<T = {}> {
48 (): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
49 (args: ReadonlyArray<string>, cwd?: string): Argv<T>;
50
51 /**
52 * Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
53 *
54 * Optionally `.alias()` can take an object that maps keys to aliases.
55 * Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
56 */
57 // Aliases for previously declared options can inherit the types of those options.
58 alias<K1 extends keyof T, K2 extends string>(shortName: K1, longName: K2 | ReadonlyArray<K2>): Argv<T & { [key in K2]: T[K1] }>;
59 alias<K1 extends keyof T, K2 extends string>(shortName: K2, longName: K1 | ReadonlyArray<K1>): Argv<T & { [key in K2]: T[K1] }>;
60 alias(shortName: string | ReadonlyArray<string>, longName: string | ReadonlyArray<string>): Argv<T>;
61 alias(aliases: { [shortName: string]: string | ReadonlyArray<string> }): Argv<T>;
62
63 /**
64 * Get the arguments as a plain old object.
65 *
66 * Arguments without a corresponding flag show up in the `argv._` array.
67 *
68 * The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl.
69 *
70 * If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js),
71 * it will ignore the first parameter since it expects it to be the script name. In order to override
72 * this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored.
73 */
74 argv: { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
75
76 /**
77 * Tell the parser to interpret `key` as an array.
78 * If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
79 * Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed as `['foo', 'bar']`
80 *
81 * When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array.
82 */
83 array<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>;
84 array<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: Array<string | number> | undefined }>;
85
86 /**
87 * Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`.
88 *
89 * `key` will default to `false`, unless a `default(key, undefined)` is explicitly set.
90 *
91 * If `key` is an array, interpret all the elements as booleans.
92 */
93 boolean<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>;
94 boolean<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: boolean | undefined }>;
95
96 /**
97 * Check that certain conditions are met in the provided arguments.
98 * @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases.
99 * If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit.
100 * @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command.
101 */
102 check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>;
103
104 /**
105 * Limit valid values for key to a predefined set of choices, given as an array or as an individual value.
106 * If this method is called multiple times, all enumerated values will be merged together.
107 * Choices are generally strings or numbers, and value matching is case-sensitive.
108 *
109 * Optionally `.choices()` can take an object that maps multiple keys to their choices.
110 *
111 * Choices can also be specified as choices in the object given to `option()`.
112 */
113 choices<K extends keyof T, C extends ReadonlyArray<any>>(key: K, values: C): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>;
114 choices<K extends string, C extends ReadonlyArray<any>>(key: K, values: C): Argv<T & { [key in K]: C[number] | undefined }>;
115 choices<C extends { [key: string]: ReadonlyArray<any> }>(choices: C): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>;
116
117 /**
118 * Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`.
119 *
120 * The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error.
121 * The returned value will be used as the value for `key` (or one of its aliases) in `argv`.
122 *
123 * If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console.
124 *
125 * Coercion will be applied to a value after all other modifications, such as `.normalize()`.
126 *
127 * Optionally `.coerce()` can take an object that maps several keys to their respective coercion function.
128 *
129 * You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`.
130 *
131 * If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed
132 */
133 coerce<K extends keyof T, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<Omit<T, K> & { [key in K]: V | undefined }>;
134 coerce<K extends string, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<T & { [key in K]: V | undefined }>;
135 coerce<O extends { [key: string]: (arg: any) => any }>(opts: O): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>;
136
137 /**
138 * Define the commands exposed by your application.
139 * @param command Should be a string representing the command or an array of strings representing the command and its aliases.
140 * @param description Use to provide a description for each command your application accepts (the values stored in `argv._`).
141 * Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion.
142 * @param [builder] Object to give hints about the options that your command accepts.
143 * Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help.
144 *
145 * Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments.
146 * @param [handler] Function, which will be executed with the parsed `argv` object.
147 */
148 command<U = T>(
149 command: string | ReadonlyArray<string>,
150 description: string,
151 builder?: BuilderCallback<T, U>,
152 handler?: (args: Arguments<U>) => void,
153 middlewares?: MiddlewareFunction[],
154 deprecated?: boolean | string,
155 ): Argv<U>;
156 command<O extends { [key: string]: Options }>(
157 command: string | ReadonlyArray<string>,
158 description: string,
159 builder?: O,
160 handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
161 middlewares?: MiddlewareFunction[],
162 deprecated?: boolean | string,
163 ): Argv<T>;
164 command<U>(command: string | ReadonlyArray<string>, description: string, module: CommandModule<T, U>): Argv<U>;
165 command<U = T>(
166 command: string | ReadonlyArray<string>,
167 showInHelp: false,
168 builder?: BuilderCallback<T, U>,
169 handler?: (args: Arguments<U>) => void,
170 middlewares?: MiddlewareFunction[],
171 deprecated?: boolean | string,
172 ): Argv<T>;
173 command<O extends { [key: string]: Options }>(
174 command: string | ReadonlyArray<string>,
175 showInHelp: false,
176 builder?: O,
177 handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
178 ): Argv<T>;
179 command<U>(command: string | ReadonlyArray<string>, showInHelp: false, module: CommandModule<T, U>): Argv<U>;
180 command<U>(module: CommandModule<T, U>): Argv<U>;
181
182 // Advanced API
183 /** Apply command modules from a directory relative to the module calling this method. */
184 commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>;
185
186 /**
187 * Enable bash/zsh-completion shortcuts for commands and options.
188 *
189 * If invoked without parameters, `.completion()` will make completion the command to output the completion script.
190 *
191 * @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted.
192 * To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (or `.zshrc` for zsh).
193 * @param [description] Provide a description in your usage instructions for the command that generates the completion scripts.
194 * @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method.
195 */
196 completion(): Argv<T>;
197 completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>;
198 completion(cmd: string, func?: SyncCompletionFunction): Argv<T>;
199 completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>;
200 completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>;
201 completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>;
202 completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>;
203
204 /**
205 * Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file.
206 * The file is loaded and parsed, and its properties are set as arguments.
207 * Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly.
208 *
209 * If invoked without parameters, `.config()` will make --config the option to pass the JSON config file.
210 *
211 * @param [description] Provided to customize the config (`key`) option in the usage string.
212 * @param [explicitConfigurationObject] An explicit configuration `object`
213 */
214 config(): Argv<T>;
215 config(key: string | ReadonlyArray<string>, description?: string, parseFn?: (configPath: string) => object): Argv<T>;
216 config(key: string | ReadonlyArray<string>, parseFn: (configPath: string) => object): Argv<T>;
217 config(explicitConfigurationObject: object): Argv<T>;
218
219 /**
220 * Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with.
221 *
222 * Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
223 */
224 conflicts(key: string, value: string | ReadonlyArray<string>): Argv<T>;
225 conflicts(conflicts: { [key: string]: string | ReadonlyArray<string> }): Argv<T>;
226
227 /**
228 * Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`.
229 */
230 count<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: number }>;
231 count<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number }>;
232
233 /**
234 * Set `argv[key]` to `value` if no option was specified in `process.argv`.
235 *
236 * Optionally `.default()` can take an object that maps keys to default values.
237 *
238 * The default value can be a `function` which returns a value. The name of the function will be used in the usage string.
239 *
240 * Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions.
241 */
242 default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>;
243 default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>;
244 default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>;
245
246 /**
247 * @deprecated since version 6.6.0
248 * Use '.demandCommand()' or '.demandOption()' instead
249 */
250 demand<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
251 demand<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>;
252 demand(key: string | ReadonlyArray<string>, required?: boolean): Argv<T>;
253 demand(positionals: number, msg: string): Argv<T>;
254 demand(positionals: number, required?: boolean): Argv<T>;
255 demand(positionals: number, max: number, msg?: string): Argv<T>;
256
257 /**
258 * @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`.
259 * If is an array, demand each element.
260 * @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message.
261 * @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters.
262 */
263 demandOption<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
264 demandOption<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>;
265 demandOption(key: string | ReadonlyArray<string>, demand?: boolean): Argv<T>;
266
267 /**
268 * Demand in context of commands.
269 * You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
270 */
271 demandCommand(): Argv<T>;
272 demandCommand(min: number, minMsg?: string): Argv<T>;
273 demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>;
274
275 /**
276 * Shows a [deprecated] notice in front of the option
277 */
278 deprecateOption(option: string, msg?: string): Argv<T>;
279
280 /**
281 * Describe a `key` for the generated usage information.
282 *
283 * Optionally `.describe()` can take an object that maps keys to descriptions.
284 */
285 describe(key: string | ReadonlyArray<string>, description: string): Argv<T>;
286 describe(descriptions: { [key: string]: string }): Argv<T>;
287
288 /** Should yargs attempt to detect the os' locale? Defaults to `true`. */
289 detectLocale(detect: boolean): Argv<T>;
290
291 /**
292 * Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments.
293 *
294 * Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo)
295 *
296 * If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv.
297 *
298 * Program arguments are defined in this order of precedence:
299 * 1. Command line args
300 * 2. Env vars
301 * 3. Config file/objects
302 * 4. Configured defaults
303 *
304 * Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration.
305 */
306 env(): Argv<T>;
307 env(prefix: string): Argv<T>;
308 env(enable: boolean): Argv<T>;
309
310 /** A message to print at the end of the usage instructions */
311 epilog(msg: string): Argv<T>;
312 /** A message to print at the end of the usage instructions */
313 epilogue(msg: string): Argv<T>;
314
315 /**
316 * Give some example invocations of your program.
317 * Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
318 * Examples will be printed out as part of the help message.
319 */
320 example(command: string, description: string): Argv<T>;
321 example(command: ReadonlyArray<[string, string?]>): Argv<T>;
322
323 /** Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by `.exitProcess().` */
324 exit(code: number, err: Error): void;
325
326 /**
327 * By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails.
328 * Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated.
329 */
330 exitProcess(enabled: boolean): Argv<T>;
331
332 /**
333 * Method to execute when a failure occurs, rather than printing the failure message.
334 * @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred.
335 */
336 fail(func: ((msg: string, err: Error, yargs: Argv<T>) => any) | boolean): Argv<T>;
337
338 /**
339 * Allows to programmatically get completion choices for any line.
340 * @param args An array of the words in the command line to complete.
341 * @param done The callback to be called with the resulting completions.
342 */
343 getCompletion(args: ReadonlyArray<string>, done: (completions: ReadonlyArray<string>) => void): Argv<T>;
344
345 /**
346 * Indicate that an option (or group of options) should not be reset when a command is executed
347 *
348 * Options default to being global.
349 */
350 global(key: string | ReadonlyArray<string>): Argv<T>;
351
352 /** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */
353 group(key: string | ReadonlyArray<string>, groupName: string): Argv<T>;
354
355 /** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */
356 hide(key: string): Argv<T>;
357
358 /**
359 * Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process.
360 * By default yargs enables help on the `--help` option.
361 *
362 * Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command.
363 * If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command.
364 *
365 * If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output.
366 *
367 * @param [description] Customizes the description of the help option in the usage string.
368 * @param [enableExplicit] If `false` is provided, it will disable --help.
369 */
370 help(): Argv<T>;
371 help(enableExplicit: boolean): Argv<T>;
372 help(option: string, enableExplicit: boolean): Argv<T>;
373 help(option: string, description?: string, enableExplicit?: boolean): Argv<T>;
374
375 /**
376 * Given the key `x` is set, it is required that the key `y` is set.
377 * y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`.
378 *
379 * Optionally `.implies()` can accept an object specifying multiple implications.
380 */
381 implies(key: string, value: string | ReadonlyArray<string>): Argv<T>;
382 implies(implies: { [key: string]: string | ReadonlyArray<string> }): Argv<T>;
383
384 /**
385 * Return the locale that yargs is currently using.
386 *
387 * By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language.
388 */
389 locale(): string;
390 /**
391 * Override the auto-detected locale from the user's operating system with a static locale.
392 * Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable.
393 */
394 locale(loc: string): Argv<T>;
395
396 /**
397 * Define global middleware functions to be called first, in list order, for all cli command.
398 * @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv.
399 * @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing.
400 */
401 middleware(callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>, applyBeforeValidation?: boolean): Argv<T>;
402
403 /**
404 * The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity.
405 *
406 * Optionally `.nargs()` can take an object of `key`/`narg` pairs.
407 */
408 nargs(key: string, count: number): Argv<T>;
409 nargs(nargs: { [key: string]: number }): Argv<T>;
410
411 /** The key provided represents a path and should have `path.normalize()` applied. */
412 normalize<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
413 normalize<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>;
414
415 /**
416 * Tell the parser to always interpret key as a number.
417 *
418 * If `key` is an array, all elements will be parsed as numbers.
419 *
420 * If the option is given on the command line without a value, `argv` will be populated with `undefined`.
421 *
422 * If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`.
423 *
424 * Note that decimals, hexadecimals, and scientific notation are all accepted.
425 */
426 number<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>;
427 number<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number | undefined }>;
428
429 /**
430 * Method to execute when a command finishes successfully.
431 * @param func Is called with the successful result of the command that finished.
432 */
433 onFinishCommand(func: (result: any) => void): Argv<T>;
434
435 /**
436 * This method can be used to make yargs aware of options that could exist.
437 * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
438 */
439 option<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
440 option<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
441 option<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
442
443 /**
444 * This method can be used to make yargs aware of options that could exist.
445 * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
446 */
447 options<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
448 options<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
449 options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
450
451 /**
452 * Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string.
453 *
454 * Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked.
455 * @param [context] Provides a useful mechanism for passing state information to commands
456 */
457 parse(): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
458 parse(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] }
459 | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
460 parseSync(): { [key in keyof Arguments<T>]: Arguments<T>[key] };
461 parseSync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] };
462 parseAsync(): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
463 parseAsync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>;
464
465 /**
466 * If the arguments have not been parsed, this property is `false`.
467 *
468 * If the arguments have been parsed, this contain detailed parsed arguments.
469 */
470 parsed: DetailedArguments | false;
471
472 /** Allows to configure advanced yargs features. */
473 parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>;
474
475 /**
476 * Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object.
477 * @param [cwd] If provided, the package.json will be read from this location
478 */
479 pkgConf(key: string | ReadonlyArray<string>, cwd?: string): Argv<T>;
480
481 /**
482 * Allows you to configure a command's positional arguments with an API similar to `.option()`.
483 * `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error.
484 */
485 positional<K extends keyof T, O extends PositionalOptions>(key: K, opt: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
486 positional<K extends string, O extends PositionalOptions>(key: K, opt: O): Argv<T & { [key in K]: InferredOptionType<O> }>;
487
488 /** Should yargs provide suggestions regarding similar commands if no matching command is found? */
489 recommendCommands(): Argv<T>;
490
491 /**
492 * @deprecated since version 6.6.0
493 * Use '.demandCommand()' or '.demandOption()' instead
494 */
495 require<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
496 require(key: string, msg: string): Argv<T>;
497 require(key: string, required: boolean): Argv<T>;
498 require(keys: ReadonlyArray<number>, msg: string): Argv<T>;
499 require(keys: ReadonlyArray<number>, required: boolean): Argv<T>;
500 require(positionals: number, required: boolean): Argv<T>;
501 require(positionals: number, msg: string): Argv<T>;
502
503 /**
504 * @deprecated since version 6.6.0
505 * Use '.demandCommand()' or '.demandOption()' instead
506 */
507 required<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>;
508 required(key: string, msg: string): Argv<T>;
509 required(key: string, required: boolean): Argv<T>;
510 required(keys: ReadonlyArray<number>, msg: string): Argv<T>;
511 required(keys: ReadonlyArray<number>, required: boolean): Argv<T>;
512 required(positionals: number, required: boolean): Argv<T>;
513 required(positionals: number, msg: string): Argv<T>;
514
515 requiresArg(key: string | ReadonlyArray<string>): Argv<T>;
516
517 /** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */
518 scriptName($0: string): Argv<T>;
519
520 /**
521 * Generate a bash completion script.
522 * Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options.
523 */
524 showCompletionScript(): Argv<T>;
525
526 /**
527 * Configure the `--show-hidden` option that displays the hidden keys (see `hide()`).
528 * @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`.
529 * If `string` it changes the key name ("--show-hidden").
530 * @param description Changes the default description ("Show hidden options")
531 */
532 showHidden(option?: string | boolean): Argv<T>;
533 showHidden(option: string, description?: string): Argv<T>;
534
535 /**
536 * Print the usage data using the console function consoleLevel for printing.
537 * @param [consoleLevel='error']
538 */
539 showHelp(consoleLevel?: string): Argv<T>;
540
541 /**
542 * Provide the usage data as a string.
543 * @param printCallback a function with a single argument.
544 */
545 showHelp(printCallback: (s: string) => void): Argv<T>;
546
547 /**
548 * By default, yargs outputs a usage string if any error is detected.
549 * Use the `.showHelpOnFail()` method to customize this behavior.
550 * @param enable If `false`, the usage string is not output.
551 * @param [message] Message that is output after the error message.
552 */
553 showHelpOnFail(enable: boolean, message?: string): Argv<T>;
554
555 /** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */
556 skipValidation(key: string | ReadonlyArray<string>): Argv<T>;
557
558 /**
559 * Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error.
560 *
561 * Unrecognized commands will also be reported as errors.
562 */
563 strict(): Argv<T>;
564 strict(enabled: boolean): Argv<T>;
565
566 /**
567 * Similar to .strict(), except that it only applies to unrecognized commands.
568 * A user can still provide arbitrary options, but unknown positional commands
569 * will raise an error.
570 */
571 strictCommands(): Argv<T>;
572 strictCommands(enabled: boolean): Argv<T>;
573
574 /**
575 * Similar to `.strict()`, except that it only applies to unrecognized options. A
576 * user can still provide arbitrary positional options, but unknown options
577 * will raise an error.
578 */
579 strictOptions(): Argv<T>;
580 strictOptions(enabled: boolean): Argv<T>;
581
582 /**
583 * Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input.
584 *
585 * If `key` is an array, interpret all the elements as strings.
586 *
587 * `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers.
588 */
589 string<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
590 string<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>;
591
592 // Intended to be used with '.wrap()'
593 terminalWidth(): number;
594
595 updateLocale(obj: { [key: string]: string }): Argv<T>;
596
597 /**
598 * Override the default strings used by yargs with the key/value pairs provided in obj
599 *
600 * If you explicitly specify a locale(), you should do so before calling `updateStrings()`.
601 */
602 updateStrings(obj: { [key: string]: string }): Argv<T>;
603
604 /**
605 * Set a usage message to show which commands to use.
606 * Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
607 *
608 * If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`.
609 * This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application
610 * and allows you to provide configuration for the positional arguments accepted by your program:
611 */
612 usage(message: string): Argv<T>;
613 usage<U>(command: string | ReadonlyArray<string>, description: string, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>;
614 usage<U>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>;
615 usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>;
616 usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>;
617
618 /**
619 * Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process.
620 * By default yargs enables version for the `--version` option.
621 *
622 * If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value.
623 *
624 * If the boolean argument `false` is provided, it will disable `--version`.
625 */
626 version(): Argv<T>;
627 version(version: string): Argv<T>;
628 version(enable: boolean): Argv<T>;
629 version(optionKey: string, version: string): Argv<T>;
630 version(optionKey: string, description: string, version: string): Argv<T>;
631
632 /**
633 * Format usage output to wrap at columns many columns.
634 *
635 * By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align).
636 * Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions.
637 */
638 wrap(columns: number | null): Argv<T>;
639 }
640
641 type Arguments<T = {}> = T & {
642 /** Non-option arguments */
643 _: Array<string | number>;
644 /** The script name or node command */
645 $0: string;
646 /** All remaining options */
647 [argName: string]: unknown;
648 };
649
650 interface RequireDirectoryOptions {
651 /** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */
652 recurse?: boolean;
653 /** The types of files to look for when requiring command modules. */
654 extensions?: ReadonlyArray<string>;
655 /**
656 * A synchronous function called for each command module encountered.
657 * Accepts `commandObject`, `pathToFile`, and `filename` as arguments.
658 * Returns `commandObject` to include the command; any falsy value to exclude/skip it.
659 */
660 visit?: (commandObject: any, pathToFile?: string, filename?: string) => any;
661 /** Whitelist certain modules */
662 include?: RegExp | ((pathToFile: string) => boolean);
663 /** Blacklist certain modules. */
664 exclude?: RegExp | ((pathToFile: string) => boolean);
665 }
666
667 interface Options {
668 /** string or array of strings, alias(es) for the canonical option key, see `alias()` */
669 alias?: string | ReadonlyArray<string>;
670 /** boolean, interpret option as an array, see `array()` */
671 array?: boolean;
672 /** boolean, interpret option as a boolean flag, see `boolean()` */
673 boolean?: boolean;
674 /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
675 choices?: Choices;
676 /** function, coerce or transform parsed command line values into another value, see `coerce()` */
677 coerce?: (arg: any) => any;
678 /** boolean, interpret option as a path to a JSON config file, see `config()` */
679 config?: boolean;
680 /** function, provide a custom config parsing function, see `config()` */
681 configParser?: (configPath: string) => object;
682 /** string or object, require certain keys not to be set, see `conflicts()` */
683 conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> };
684 /** boolean, interpret option as a count of boolean flags, see `count()` */
685 count?: boolean;
686 /** value, set a default value for the option, see `default()` */
687 default?: any;
688 /** string, use this description for the default value in help content, see `default()` */
689 defaultDescription?: string;
690 /**
691 * @deprecated since version 6.6.0
692 * Use 'demandOption' instead
693 */
694 demand?: boolean | string;
695 /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
696 deprecate?: boolean | string;
697 /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
698 deprecated?: boolean | string;
699 /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
700 demandOption?: boolean | string;
701 /** string, the option description for help content, see `describe()` */
702 desc?: string;
703 /** string, the option description for help content, see `describe()` */
704 describe?: string;
705 /** string, the option description for help content, see `describe()` */
706 description?: string;
707 /** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */
708 global?: boolean;
709 /** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */
710 group?: string;
711 /** don't display option in help output. */
712 hidden?: boolean;
713 /** string or object, require certain keys to be set, see `implies()` */
714 implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> };
715 /** number, specify how many arguments should be consumed for the option, see `nargs()` */
716 nargs?: number;
717 /** boolean, apply path.normalize() to the option, see `normalize()` */
718 normalize?: boolean;
719 /** boolean, interpret option as a number, `number()` */
720 number?: boolean;
721 /**
722 * @deprecated since version 6.6.0
723 * Use 'demandOption' instead
724 */
725 require?: boolean | string;
726 /**
727 * @deprecated since version 6.6.0
728 * Use 'demandOption' instead
729 */
730 required?: boolean | string;
731 /** boolean, require the option be specified with a value, see `requiresArg()` */
732 requiresArg?: boolean;
733 /** boolean, skips validation if the option is present, see `skipValidation()` */
734 skipValidation?: boolean;
735 /** boolean, interpret option as a string, see `string()` */
736 string?: boolean;
737 type?: "array" | "count" | PositionalOptionsType;
738 }
739
740 interface PositionalOptions {
741 /** string or array of strings, see `alias()` */
742 alias?: string | ReadonlyArray<string>;
743 /** boolean, interpret option as an array, see `array()` */
744 array?: boolean;
745 /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
746 choices?: Choices;
747 /** function, coerce or transform parsed command line values into another value, see `coerce()` */
748 coerce?: (arg: any) => any;
749 /** string or object, require certain keys not to be set, see `conflicts()` */
750 conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> };
751 /** value, set a default value for the option, see `default()` */
752 default?: any;
753 /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
754 demandOption?: boolean | string;
755 /** string, the option description for help content, see `describe()` */
756 desc?: string;
757 /** string, the option description for help content, see `describe()` */
758 describe?: string;
759 /** string, the option description for help content, see `describe()` */
760 description?: string;
761 /** string or object, require certain keys to be set, see `implies()` */
762 implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> };
763 /** boolean, apply path.normalize() to the option, see normalize() */
764 normalize?: boolean;
765 type?: PositionalOptionsType;
766 }
767
768 /** Remove keys K in T */
769 type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] };
770
771 /** Remove undefined as a possible value for keys K in T */
772 type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> };
773
774 /** Convert T to T[] and T | undefined to T[] | undefined */
775 type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>;
776
777 /** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */
778 type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>;
779
780 /** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */
781 type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;
782
783 type InferredOptionType<O extends Options | PositionalOptions> =
784 O extends (
785 | { required: string | true }
786 | { require: string | true }
787 | { demand: string | true }
788 | { demandOption: string | true }
789 ) ?
790 Exclude<InferredOptionTypeInner<O>, undefined> :
791 InferredOptionTypeInner<O>;
792
793 type InferredOptionTypeInner<O extends Options | PositionalOptions> =
794 O extends { default: any, coerce: (arg: any) => infer T } ? T :
795 O extends { default: infer D } ? D :
796 O extends { type: "count" } ? number :
797 O extends { count: true } ? number :
798 RequiredOptionType<O> | undefined;
799
800 type RequiredOptionType<O extends Options | PositionalOptions> =
801 O extends { type: "array", string: true } ? string[] :
802 O extends { type: "array", number: true } ? number[] :
803 O extends { type: "array", normalize: true } ? string[] :
804 O extends { type: "string", array: true } ? string[] :
805 O extends { type: "number", array: true } ? number[] :
806 O extends { string: true, array: true } ? string[] :
807 O extends { number: true, array: true } ? number[] :
808 O extends { normalize: true, array: true } ? string[] :
809 O extends { type: "array" } ? Array<string | number> :
810 O extends { type: "boolean" } ? boolean :
811 O extends { type: "number" } ? number :
812 O extends { type: "string" } ? string :
813 O extends { array: true } ? Array<string | number> :
814 O extends { boolean: true } ? boolean :
815 O extends { number: true } ? number :
816 O extends { string: true } ? string :
817 O extends { normalize: true } ? string :
818 O extends { choices: ReadonlyArray<infer C> } ? C :
819 O extends { coerce: (arg: any) => infer T } ? T :
820 unknown;
821
822 type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> };
823
824 interface CommandModule<T = {}, U = {}> {
825 /** array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored */
826 aliases?: ReadonlyArray<string> | string;
827 /** object declaring the options the command accepts, or a function accepting and returning a yargs instance */
828 builder?: CommandBuilder<T, U>;
829 /** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */
830 command?: ReadonlyArray<string> | string;
831 /** boolean (or string) to show deprecation notice */
832 deprecated?: boolean | string;
833 /** string used as the description for the command in help text, use `false` for a hidden command */
834 describe?: string | false;
835 /** a function which will be passed the parsed argv. */
836 handler: (args: Arguments<U>) => void;
837 }
838
839 type ParseCallback<T = {}> = (err: Error | undefined, argv: Arguments<T>|Promise<Arguments<T>>, output: string) => void;
840 type CommandBuilder<T = {}, U = {}> = { [key: string]: Options } | ((args: Argv<T>) => Argv<U>) | ((args: Argv<T>) => PromiseLike<Argv<U>>);
841 type SyncCompletionFunction = (current: string, argv: any) => string[];
842 type AsyncCompletionFunction = (current: string, argv: any, done: (completion: ReadonlyArray<string>) => void) => void;
843 type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>;
844 type MiddlewareFunction<T = {}> = (args: Arguments<T>) => void;
845 type Choices = ReadonlyArray<string | number | true | undefined>;
846 type PositionalOptionsType = "boolean" | "number" | "string";
847}
848
849declare var yargs: yargs.Argv;
850export = yargs;