id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
2,900
( argv: Arguments, _yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { return f(argv, _yargs.getOptions()); }, (result: any): Partial<Arguments> | Promise<Partial<Arguments>> => { if (!result) { this.#usage.fail( this.#shim.y18n.__('Argument check failed: %s', f.toString()) ); } else if (typeof result === 'string' || result instanceof Error) { this.#usage.fail(result.toString(), result); } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { this.#usage.fail(err.message ? err.message : err.toString(), err); return argv; } ); }
class YargsInstance { $0: string; argv?: Arguments; customScriptName = false; parsed: DetailedArguments | false = false; #command: CommandInstance; #cwd: string; // use context object to keep track of resets, subcommand execution, etc., // submodules should modify and check the state of context as necessary: #context: Context = {commands: [], fullCommands: []}; #completion: CompletionInstance | null = null; #completionCommand: string | null = null; #defaultShowHiddenOpt = 'show-hidden'; #exitError: YError | string | nil = null; #detectLocale = true; #emittedWarnings: Dictionary<boolean> = {}; #exitProcess = true; #frozens: FrozenYargsInstance[] = []; #globalMiddleware: GlobalMiddleware; #groups: Dictionary<string[]> = {}; #hasOutput = false; #helpOpt: string | null = null; #isGlobalContext = true; #logger: LoggerInstance; #output = ''; #options: Options; #parentRequire?: RequireType; #parserConfig: Configuration = {}; #parseFn: ParseCallback | null = null; #parseContext: object | null = null; #pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {}; #preservedGroups: Dictionary<string[]> = {}; #processArgs: string | string[]; #recommendCommands = false; #shim: PlatformShim; #strict = false; #strictCommands = false; #strictOptions = false; #usage: UsageInstance; #usageConfig: UsageConfiguration = {}; #versionOpt: string | null = null; #validation: ValidationInstance; constructor( processArgs: string | string[] = [], cwd: string, parentRequire: RequireType | undefined, shim: PlatformShim ) { this.#shim = shim; this.#processArgs = processArgs; this.#cwd = cwd; this.#parentRequire = parentRequire; this.#globalMiddleware = new GlobalMiddleware(this); this.$0 = this[kGetDollarZero](); // #command, #validation, and #usage are initialized on first reset: this[kReset](); this.#command = this!.#command; this.#usage = this!.#usage; this.#validation = this!.#validation; this.#options = this!.#options; this.#options.showHiddenOpt = this.#defaultShowHiddenOpt; this.#logger = this[kCreateLogger](); } addHelpOpt(opt?: string | false, msg?: string): YargsInstance { const defaultHelpOpt = 'help'; argsert('[string|boolean] [string]', [opt, msg], arguments.length); // nuke the key previously configured // to return help. if (this.#helpOpt) { this[kDeleteFromParserHintObject](this.#helpOpt); this.#helpOpt = null; } if (opt === false && msg === undefined) return this; // use arguments, fallback to defaults for opt and msg this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt; this.boolean(this.#helpOpt); this.describe( this.#helpOpt, msg || this.#usage.deferY18nLookup('Show help') ); return this; } help(opt?: string, msg?: string): YargsInstance { return this.addHelpOpt(opt, msg); } addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance { argsert('[string|boolean] [string]', [opt, msg], arguments.length); if (opt === false && msg === undefined) return this; const showHiddenOpt = typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt; this.boolean(showHiddenOpt); this.describe( showHiddenOpt, msg || this.#usage.deferY18nLookup('Show hidden options') ); this.#options.showHiddenOpt = showHiddenOpt; return this; } showHidden(opt?: string | false, msg?: string): YargsInstance { return this.addShowHiddenOpt(opt, msg); } alias( key: string | string[] | Dictionary<string | string[]>, value?: string | string[] ): YargsInstance { argsert( '<object|string|array> [string|array]', [key, value], arguments.length ); this[kPopulateParserHintArrayDictionary]( this.alias.bind(this), 'alias', key, value ); return this; } array(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('array', keys); this[kTrackManuallySetKeys](keys); return this; } boolean(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('boolean', keys); this[kTrackManuallySetKeys](keys); return this; } check( f: (argv: Arguments, options: Options) => any, global?: boolean ): YargsInstance { argsert('<function> [boolean]', [f, global], arguments.length); this.middleware( ( argv: Arguments, _yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { return f(argv, _yargs.getOptions()); }, (result: any): Partial<Arguments> | Promise<Partial<Arguments>> => { if (!result) { this.#usage.fail( this.#shim.y18n.__('Argument check failed: %s', f.toString()) ); } else if (typeof result === 'string' || result instanceof Error) { this.#usage.fail(result.toString(), result); } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { this.#usage.fail(err.message ? err.message : err.toString(), err); return argv; } ); }, false, global ); return this; } choices( key: string | string[] | Dictionary<string | string[]>, value?: string | string[] ): YargsInstance { argsert( '<object|string|array> [string|array]', [key, value], arguments.length ); this[kPopulateParserHintArrayDictionary]( this.choices.bind(this), 'choices', key, value ); return this; } coerce( keys: string | string[] | Dictionary<CoerceCallback>, value?: CoerceCallback ): YargsInstance { argsert( '<object|string|array> [function]', [keys, value], arguments.length ); if (Array.isArray(keys)) { if (!value) { throw new YError('coerce callback must be provided'); } for (const key of keys) { this.coerce(key, value); } return this; } else if (typeof keys === 'object') { for (const key of Object.keys(keys)) { this.coerce(key, keys[key]); } return this; } if (!value) { throw new YError('coerce callback must be provided'); } // This noop tells yargs-parser about the existence of the option // represented by "keys", so that it can apply camel case expansion // if needed: this.#options.key[keys] = true; this.#globalMiddleware.addCoerceMiddleware( ( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }, keys ); return this; } conflicts( key1: string | Dictionary<string | string[]>, key2?: string | string[] ): YargsInstance { argsert('<string|object> [string|array]', [key1, key2], arguments.length); this.#validation.conflicts(key1, key2); return this; } config( key: string | string[] | Dictionary = 'config', msg?: string | ConfigCallback, parseFn?: ConfigCallback ): YargsInstance { argsert( '[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length ); // allow a config object to be provided directly. if (typeof key === 'object' && !Array.isArray(key)) { key = applyExtends( key, this.#cwd, this[kGetParserConfiguration]()['deep-merge-config'] || false, this.#shim ); this.#options.configObjects = (this.#options.configObjects || []).concat( key ); return this; } // allow for a custom parsing function. if (typeof msg === 'function') { parseFn = msg; msg = undefined; } this.describe( key, msg || this.#usage.deferY18nLookup('Path to JSON config file') ); (Array.isArray(key) ? key : [key]).forEach(k => { this.#options.config[k] = parseFn || true; }); return this; } completion( cmd?: string, desc?: string | false | CompletionFunction, fn?: CompletionFunction ): YargsInstance { argsert( '[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length ); // a function to execute when generating // completions can be provided as the second // or third argument to completion. if (typeof desc === 'function') { fn = desc; desc = undefined; } // register the completion command. this.#completionCommand = cmd || this.#completionCommand || 'completion'; if (!desc && desc !== false) { desc = 'generate completion script'; } this.command(this.#completionCommand, desc); // a function can be provided if (fn) this.#completion!.registerFunction(fn); return this; } command( cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[], description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, middlewares?: Middleware[], deprecated?: boolean ): YargsInstance { argsert( '<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length ); this.#command.addHandler( cmd, description, builder, handler, middlewares, deprecated ); return this; } commands( cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[], description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, middlewares?: Middleware[], deprecated?: boolean ): YargsInstance { return this.command( cmd, description, builder, handler, middlewares, deprecated ); } commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance { argsert('<string> [object]', [dir, opts], arguments.length); const req = this.#parentRequire || this.#shim.require; this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts); return this; } count(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('count', keys); this[kTrackManuallySetKeys](keys); return this; } default( key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string ): YargsInstance { argsert( '<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length ); if (defaultDescription) { assertSingleKey(key, this.#shim); this.#options.defaultDescription[key] = defaultDescription; } if (typeof value === 'function') { assertSingleKey(key, this.#shim); if (!this.#options.defaultDescription[key]) this.#options.defaultDescription[key] = this.#usage.functionDescription(value); value = value.call(); } this[kPopulateParserHintSingleValueDictionary]<'default'>( this.default.bind(this), 'default', key, value ); return this; } defaults( key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string ): YargsInstance { return this.default(key, value, defaultDescription); } demandCommand( min = 1, max?: number | string, minMsg?: string | null, maxMsg?: string | null ): YargsInstance { argsert( '[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length ); if (typeof max !== 'number') { minMsg = max; max = Infinity; } this.global('_', false); this.#options.demandedCommands._ = { min, max, minMsg, maxMsg, }; return this; } demand( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { // you can optionally provide a 'max' key, // which will raise an exception if too many '_' // options are provided. if (Array.isArray(max)) { max.forEach(key => { assertNotStrictEqual(msg, true as const, this.#shim); this.demandOption(key, msg); }); max = Infinity; } else if (typeof max !== 'number') { msg = max; max = Infinity; } if (typeof keys === 'number') { assertNotStrictEqual(msg, true as const, this.#shim); this.demandCommand(keys, max, msg, msg); } else if (Array.isArray(keys)) { keys.forEach(key => { assertNotStrictEqual(msg, true as const, this.#shim); this.demandOption(key, msg); }); } else { if (typeof msg === 'string') { this.demandOption(keys, msg); } else if (msg === true || typeof msg === 'undefined') { this.demandOption(keys); } } return this; } demandOption( keys: string | string[] | Dictionary<string | undefined>, msg?: string ): YargsInstance { argsert('<object|string|array> [string]', [keys, msg], arguments.length); this[kPopulateParserHintSingleValueDictionary]( this.demandOption.bind(this), 'demandedOptions', keys, msg ); return this; } deprecateOption(option: string, message: string | boolean): YargsInstance { argsert('<string> [string|boolean]', [option, message], arguments.length); this.#options.deprecatedOptions[option] = message; return this; } describe( keys: string | string[] | Dictionary<string>, description?: string ): YargsInstance { argsert( '<object|string|array> [string]', [keys, description], arguments.length ); this[kSetKey](keys, true); this.#usage.describe(keys, description); return this; } detectLocale(detect: boolean): YargsInstance { argsert('<boolean>', [detect], arguments.length); this.#detectLocale = detect; return this; } // as long as options.envPrefix is not undefined, // parser will apply env vars matching prefix to argv env(prefix?: string | false): YargsInstance { argsert('[string|boolean]', [prefix], arguments.length); if (prefix === false) delete this.#options.envPrefix; else this.#options.envPrefix = prefix || ''; return this; } epilogue(msg: string): YargsInstance { argsert('<string>', [msg], arguments.length); this.#usage.epilog(msg); return this; } epilog(msg: string): YargsInstance { return this.epilogue(msg); } example( cmd: string | [string, string?][], description?: string ): YargsInstance { argsert('<string|array> [string]', [cmd, description], arguments.length); if (Array.isArray(cmd)) { cmd.forEach(exampleParams => this.example(...exampleParams)); } else { this.#usage.example(cmd, description); } return this; } // maybe exit, always capture context about why we wanted to exit: exit(code: number, err?: YError | string): void { this.#hasOutput = true; this.#exitError = err; if (this.#exitProcess) this.#shim.process.exit(code); } exitProcess(enabled = true): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#exitProcess = enabled; return this; } fail(f: FailureFunction | boolean): YargsInstance { argsert('<function|boolean>', [f], arguments.length); if (typeof f === 'boolean' && f !== false) { throw new YError( "Invalid first argument. Expected function or boolean 'false'" ); } this.#usage.failFn(f); return this; } getAliases(): Dictionary<string[]> { return this.parsed ? this.parsed.aliases : {}; } async getCompletion( args: string[], done?: (err: Error | null, completions: string[] | undefined) => void ): Promise<string[] | void> { argsert('<array> [function]', [args, done], arguments.length); if (!done) { return new Promise((resolve, reject) => { this.#completion!.getCompletion(args, (err, completions) => { if (err) reject(err); else resolve(completions); }); }); } else { return this.#completion!.getCompletion(args, done); } } getDemandedOptions() { argsert([], 0); return this.#options.demandedOptions; } getDemandedCommands() { argsert([], 0); return this.#options.demandedCommands; } getDeprecatedOptions() { argsert([], 0); return this.#options.deprecatedOptions; } getDetectLocale(): boolean { return this.#detectLocale; } getExitProcess(): boolean { return this.#exitProcess; } // combine explicit and preserved groups. explicit groups should be first getGroups(): Dictionary<string[]> { return Object.assign({}, this.#groups, this.#preservedGroups); } getHelp(): Promise<string> { this.#hasOutput = true; if (!this.#usage.hasCachedHelpMessage()) { if (!this.parsed) { // Run the parser as if --help was passed to it (this is what // the last parameter `true` indicates). const parse = this[kRunYargsParserAndExecuteCommands]( this.#processArgs, undefined, undefined, 0, true ); if (isPromise(parse)) { return parse.then(() => { return this.#usage.help(); }); } } // Ensure top level options/positionals have been configured: const builderResponse = this.#command.runDefaultBuilderOn(this); if (isPromise(builderResponse)) { return builderResponse.then(() => { return this.#usage.help(); }); } } return Promise.resolve(this.#usage.help()); } getOptions(): Options { return this.#options; } getStrict(): boolean { return this.#strict; } getStrictCommands(): boolean { return this.#strictCommands; } getStrictOptions(): boolean { return this.#strictOptions; } global(globals: string | string[], global?: boolean): YargsInstance { argsert('<string|array> [boolean]', [globals, global], arguments.length); globals = ([] as string[]).concat(globals); if (global !== false) { this.#options.local = this.#options.local.filter( l => globals.indexOf(l) === -1 ); } else { globals.forEach(g => { if (!this.#options.local.includes(g)) this.#options.local.push(g); }); } return this; } group(opts: string | string[], groupName: string): YargsInstance { argsert('<string|array> <string>', [opts, groupName], arguments.length); const existing = this.#preservedGroups[groupName] || this.#groups[groupName]; if (this.#preservedGroups[groupName]) { // we now only need to track this group name in groups. delete this.#preservedGroups[groupName]; } const seen: Dictionary<boolean> = {}; this.#groups[groupName] = (existing || []).concat(opts).filter(key => { if (seen[key]) return false; return (seen[key] = true); }); return this; } hide(key: string): YargsInstance { argsert('<string>', [key], arguments.length); this.#options.hiddenOptions.push(key); return this; } implies( key: string | Dictionary<KeyOrPos | KeyOrPos[]>, value?: KeyOrPos | KeyOrPos[] ): YargsInstance { argsert( '<string|object> [number|string|array]', [key, value], arguments.length ); this.#validation.implies(key, value); return this; } locale(locale?: string): YargsInstance | string { argsert('[string]', [locale], arguments.length); if (locale === undefined) { this[kGuessLocale](); return this.#shim.y18n.getLocale(); } this.#detectLocale = false; this.#shim.y18n.setLocale(locale); return this; } middleware( callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean, global?: boolean ): YargsInstance { return this.#globalMiddleware.addMiddleware( callback, !!applyBeforeValidation, global ); } nargs( key: string | string[] | Dictionary<number>, value?: number ): YargsInstance { argsert('<string|object|array> [number]', [key, value], arguments.length); this[kPopulateParserHintSingleValueDictionary]( this.nargs.bind(this), 'narg', key, value ); return this; } normalize(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('normalize', keys); return this; } number(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('number', keys); this[kTrackManuallySetKeys](keys); return this; } option( key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition ): YargsInstance { argsert('<string|object> [object]', [key, opt], arguments.length); if (typeof key === 'object') { Object.keys(key).forEach(k => { this.options(k, key[k]); }); } else { if (typeof opt !== 'object') { opt = {}; } this[kTrackManuallySetKeys](key); // Warn about version name collision // Addresses: https://github.com/yargs/yargs/issues/1979 if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) { this[kEmitWarning]( [ '"version" is a reserved word.', 'Please do one of the following:', '- Disable version with `yargs.version(false)` if using "version" as an option', '- Use the built-in `yargs.version` method instead (if applicable)', '- Use a different option key', 'https://yargs.js.org/docs/#api-reference-version', ].join('\n'), undefined, 'versionWarning' // TODO: better dedupeId ); } this.#options.key[key] = true; // track manually set keys. if (opt.alias) this.alias(key, opt.alias); const deprecate = opt.deprecate || opt.deprecated; if (deprecate) { this.deprecateOption(key, deprecate); } const demand = opt.demand || opt.required || opt.require; // A required option can be specified via "demand: true". if (demand) { this.demand(key, demand); } if (opt.demandOption) { this.demandOption( key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined ); } if (opt.conflicts) { this.conflicts(key, opt.conflicts); } if ('default' in opt) { this.default(key, opt.default); } if (opt.implies !== undefined) { this.implies(key, opt.implies); } if (opt.nargs !== undefined) { this.nargs(key, opt.nargs); } if (opt.config) { this.config(key, opt.configParser); } if (opt.normalize) { this.normalize(key); } if (opt.choices) { this.choices(key, opt.choices); } if (opt.coerce) { this.coerce(key, opt.coerce); } if (opt.group) { this.group(key, opt.group); } if (opt.boolean || opt.type === 'boolean') { this.boolean(key); if (opt.alias) this.boolean(opt.alias); } if (opt.array || opt.type === 'array') { this.array(key); if (opt.alias) this.array(opt.alias); } if (opt.number || opt.type === 'number') { this.number(key); if (opt.alias) this.number(opt.alias); } if (opt.string || opt.type === 'string') { this.string(key); if (opt.alias) this.string(opt.alias); } if (opt.count || opt.type === 'count') { this.count(key); } if (typeof opt.global === 'boolean') { this.global(key, opt.global); } if (opt.defaultDescription) { this.#options.defaultDescription[key] = opt.defaultDescription; } if (opt.skipValidation) { this.skipValidation(key); } const desc = opt.describe || opt.description || opt.desc; const descriptions = this.#usage.getDescriptions(); if ( !Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc === 'string' ) { this.describe(key, desc); } if (opt.hidden) { this.hide(key); } if (opt.requiresArg) { this.requiresArg(key); } } return this; } options( key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition ): YargsInstance { return this.option(key, opt); } parse( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Arguments | Promise<Arguments> { argsert( '[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length ); this[kFreeze](); // Push current state of parser onto stack. if (typeof args === 'undefined') { args = this.#processArgs; } // a context object can optionally be provided, this allows // additional information to be passed to a command handler. if (typeof shortCircuit === 'object') { this.#parseContext = shortCircuit; shortCircuit = _parseFn; } // by providing a function as a second argument to // parse you can capture output that would otherwise // default to printing to stdout/stderr. if (typeof shortCircuit === 'function') { this.#parseFn = shortCircuit as ParseCallback; shortCircuit = false; } // completion short-circuits the parsing process, // skipping validation, etc. if (!shortCircuit) this.#processArgs = args; if (this.#parseFn) this.#exitProcess = false; const parsed = this[kRunYargsParserAndExecuteCommands]( args, !!shortCircuit ); const tmpParsed = this.parsed; this.#completion!.setParsed(this.parsed as DetailedArguments); if (isPromise(parsed)) { return parsed .then(argv => { if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output); return argv; }) .catch(err => { if (this.#parseFn) { this.#parseFn!( err, (this.parsed as DetailedArguments).argv, this.#output ); } throw err; }) .finally(() => { this[kUnfreeze](); // Pop the stack. this.parsed = tmpParsed; }); } else { if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output); this[kUnfreeze](); // Pop the stack. this.parsed = tmpParsed; } return parsed; } parseAsync( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Promise<Arguments> { const maybePromise = this.parse(args, shortCircuit, _parseFn); return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise; } parseSync( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Arguments { const maybePromise = this.parse(args, shortCircuit, _parseFn); if (isPromise(maybePromise)) { throw new YError( '.parseSync() must not be used with asynchronous builders, handlers, or middleware' ); } return maybePromise; } parserConfiguration(config: Configuration) { argsert('<object>', [config], arguments.length); this.#parserConfig = config; return this; } pkgConf(key: string, rootPath?: string): YargsInstance { argsert('<string> [string]', [key, rootPath], arguments.length); let conf = null; // prefer cwd to require-main-filename in this method // since we're looking for e.g. "nyc" config in nyc consumer // rather than "yargs" config in nyc (where nyc is the main filename) const obj = this[kPkgUp](rootPath || this.#cwd); // If an object exists in the key, add it to options.configObjects if (obj[key] && typeof obj[key] === 'object') { conf = applyExtends( obj[key] as {[key: string]: string}, rootPath || this.#cwd, this[kGetParserConfiguration]()['deep-merge-config'] || false, this.#shim ); this.#options.configObjects = (this.#options.configObjects || []).concat( conf ); } return this; } positional(key: string, opts: PositionalDefinition): YargsInstance { argsert('<string> <object>', [key, opts], arguments.length); // .positional() only supports a subset of the configuration // options available to .option(): const supportedOpts: (keyof PositionalDefinition)[] = [ 'default', 'defaultDescription', 'implies', 'normalize', 'choices', 'conflicts', 'coerce', 'type', 'describe', 'desc', 'description', 'alias', ]; opts = objFilter(opts, (k, v) => { // type can be one of string|number|boolean. if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) return false; return supportedOpts.includes(k); }); // copy over any settings that can be inferred from the command string. const fullCommand = this.#context.fullCommands[this.#context.fullCommands.length - 1]; const parseOptions = fullCommand ? this.#command.cmdToParseOptions(fullCommand) : { array: [], alias: {}, default: {}, demand: {}, }; objectKeys(parseOptions).forEach(pk => { const parseOption = parseOptions[pk]; if (Array.isArray(parseOption)) { if (parseOption.indexOf(key) !== -1) opts[pk] = true; } else { if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key]; } }); this.group(key, this.#usage.getPositionalGroupName()); return this.option(key, opts); } recommendCommands(recommend = true): YargsInstance { argsert('[boolean]', [recommend], arguments.length); this.#recommendCommands = recommend; return this; } required( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { return this.demand(keys, max, msg); } require( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { return this.demand(keys, max, msg); } requiresArg(keys: string | string[] | Dictionary): YargsInstance { // the 2nd paramter [number] in the argsert the assertion is mandatory // as populateParserHintSingleValueDictionary recursively calls requiresArg // with Nan as a 2nd parameter, although we ignore it argsert('<array|string|object> [number]', [keys], arguments.length); // If someone configures nargs at the same time as requiresArg, // nargs should take precedence, // see: https://github.com/yargs/yargs/pull/1572 // TODO: make this work with aliases, using a check similar to // checkAllAliases() in yargs-parser. if (typeof keys === 'string' && this.#options.narg[keys]) { return this; } else { this[kPopulateParserHintSingleValueDictionary]( this.requiresArg.bind(this), 'narg', keys, NaN ); } return this; } showCompletionScript($0?: string, cmd?: string): YargsInstance { argsert('[string] [string]', [$0, cmd], arguments.length); $0 = $0 || this.$0; this.#logger.log( this.#completion!.generateCompletionScript( $0, cmd || this.#completionCommand || 'completion' ) ); return this; } showHelp( level: 'error' | 'log' | ((message: string) => void) ): YargsInstance { argsert('[string|function]', [level], arguments.length); this.#hasOutput = true; if (!this.#usage.hasCachedHelpMessage()) { if (!this.parsed) { // Run the parser as if --help was passed to it (this is what // the last parameter `true` indicates). const parse = this[kRunYargsParserAndExecuteCommands]( this.#processArgs, undefined, undefined, 0, true ); if (isPromise(parse)) { parse.then(() => { this.#usage.showHelp(level); }); return this; } } // Ensure top level options/positionals have been configured: const builderResponse = this.#command.runDefaultBuilderOn(this); if (isPromise(builderResponse)) { builderResponse.then(() => { this.#usage.showHelp(level); }); return this; } } this.#usage.showHelp(level); return this; } scriptName(scriptName: string): YargsInstance { this.customScriptName = true; this.$0 = scriptName; return this; } showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance { argsert('[boolean|string] [string]', [enabled, message], arguments.length); this.#usage.showHelpOnFail(enabled, message); return this; } showVersion( level: 'error' | 'log' | ((message: string) => void) ): YargsInstance { argsert('[string|function]', [level], arguments.length); this.#usage.showVersion(level); return this; } skipValidation(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('skipValidation', keys); return this; } strict(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strict = enabled !== false; return this; } strictCommands(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strictCommands = enabled !== false; return this; } strictOptions(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strictOptions = enabled !== false; return this; } string(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('string', keys); this[kTrackManuallySetKeys](keys); return this; } terminalWidth(): number | null { argsert([], 0); return this.#shim.process.stdColumns; } updateLocale(obj: Dictionary<string>): YargsInstance { return this.updateStrings(obj); } updateStrings(obj: Dictionary<string>): YargsInstance { argsert('<object>', [obj], arguments.length); this.#detectLocale = false; this.#shim.y18n.updateLocale(obj); return this; } usage( msg: string | null, description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback ): YargsInstance { argsert( '<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length ); if (description !== undefined) { assertNotStrictEqual(msg, null, this.#shim); // .usage() can be used as an alias for defining // a default command. if ((msg || '').match(/^\$0( |$)/)) { return this.command(msg, description, builder, handler); } else { throw new YError( '.usage() description must start with $0 if being used as alias for .command()' ); } } else { this.#usage.usage(msg); return this; } } usageConfiguration(config: UsageConfiguration) { argsert('<object>', [config], arguments.length); this.#usageConfig = config; return this; } version(opt?: string | false, msg?: string, ver?: string): YargsInstance { const defaultVersionOpt = 'version'; argsert( '[boolean|string] [string] [string]', [opt, msg, ver], arguments.length ); // nuke the key previously configured // to return version #. if (this.#versionOpt) { this[kDeleteFromParserHintObject](this.#versionOpt); this.#usage.version(undefined); this.#versionOpt = null; } if (arguments.length === 0) { ver = this[kGuessVersion](); opt = defaultVersionOpt; } else if (arguments.length === 1) { if (opt === false) { // disable default 'version' key. return this; } ver = opt; opt = defaultVersionOpt; } else if (arguments.length === 2) { ver = msg; msg = undefined; } this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt; msg = msg || this.#usage.deferY18nLookup('Show version number'); this.#usage.version(ver || undefined); this.boolean(this.#versionOpt); this.describe(this.#versionOpt, msg); return this; } wrap(cols: number | nil): YargsInstance { argsert('<number|null|undefined>', [cols], arguments.length); this.#usage.wrap(cols); return this; } // to simplify the parsing of positionals in commands, // we temporarily populate '--' rather than _, with arguments // after the '--' directive. After the parse, we copy these back. [kCopyDoubleDash](argv: Arguments): any { if (!argv._ || !argv['--']) return argv; // eslint-disable-next-line prefer-spread argv._.push.apply(argv._, argv['--']); // We catch an error here, in case someone has called Object.seal() // on the parsed object, see: https://github.com/babel/babel/pull/10733 try { delete argv['--']; // eslint-disable-next-line no-empty } catch (_err) {} return argv; } [kCreateLogger](): LoggerInstance { return { log: (...args: any[]) => { if (!this[kHasParseCallback]()) console.log(...args); this.#hasOutput = true; if (this.#output.length) this.#output += '\n'; this.#output += args.join(' '); }, error: (...args: any[]) => { if (!this[kHasParseCallback]()) console.error(...args); this.#hasOutput = true; if (this.#output.length) this.#output += '\n'; this.#output += args.join(' '); }, }; } [kDeleteFromParserHintObject](optionKey: string) { // delete from all parsing hints: // boolean, array, key, alias, etc. objectKeys(this.#options).forEach((hintKey: keyof Options) => { // configObjects is not a parsing hint array if (((key): key is 'configObjects' => key === 'configObjects')(hintKey)) return; const hint = this.#options[hintKey]; if (Array.isArray(hint)) { if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1); } else if (typeof hint === 'object') { delete (hint as Dictionary)[optionKey]; } }); // now delete the description from usage.js. delete this.#usage.getDescriptions()[optionKey]; } [kEmitWarning]( warning: string, type: string | undefined, deduplicationId: string ) { // prevent duplicate warning emissions if (!this.#emittedWarnings[deduplicationId]) { this.#shim.process.emitWarning(warning, type); this.#emittedWarnings[deduplicationId] = true; } } [kFreeze]() { this.#frozens.push({ options: this.#options, configObjects: this.#options.configObjects.slice(0), exitProcess: this.#exitProcess, groups: this.#groups, strict: this.#strict, strictCommands: this.#strictCommands, strictOptions: this.#strictOptions, completionCommand: this.#completionCommand, output: this.#output, exitError: this.#exitError!, hasOutput: this.#hasOutput, parsed: this.parsed, parseFn: this.#parseFn!, parseContext: this.#parseContext, }); this.#usage.freeze(); this.#validation.freeze(); this.#command.freeze(); this.#globalMiddleware.freeze(); } [kGetDollarZero](): string { let $0 = ''; // ignore the node bin, specify this in your // bin file with #!/usr/bin/env node let default$0: string[]; if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) { default$0 = this.#shim.process.argv().slice(1, 2); } else { default$0 = this.#shim.process.argv().slice(0, 1); } $0 = default$0 .map(x => { const b = this[kRebase](this.#cwd, x); return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; }) .join(' ') .trim(); if ( this.#shim.getEnv('_') && this.#shim.getProcessArgvBin() === this.#shim.getEnv('_') ) { $0 = this.#shim .getEnv('_')! .replace( `${this.#shim.path.dirname(this.#shim.process.execPath())}/`, '' ); } return $0; } [kGetParserConfiguration](): Configuration { return this.#parserConfig; } [kGetUsageConfiguration](): UsageConfiguration { return this.#usageConfig; } [kGuessLocale]() { if (!this.#detectLocale) return; const locale = this.#shim.getEnv('LC_ALL') || this.#shim.getEnv('LC_MESSAGES') || this.#shim.getEnv('LANG') || this.#shim.getEnv('LANGUAGE') || 'en_US'; this.locale(locale.replace(/[.:].*/, '')); } [kGuessVersion](): string { const obj = this[kPkgUp](); return (obj.version as string) || 'unknown'; } // We wait to coerce numbers for positionals until after the initial parse. // This allows commands to configure number parsing on a positional by // positional basis: [kParsePositionalNumbers](argv: Arguments): any { const args: (string | number)[] = argv['--'] ? argv['--'] : argv._; for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { if ( this.#shim.Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`))) ) { args[i] = Number(arg); } } return argv; } [kPkgUp](rootPath?: string) { const npath = rootPath || '*'; if (this.#pkgs[npath]) return this.#pkgs[npath]; let obj = {}; try { let startDir = rootPath || this.#shim.mainFilename; // When called in an environment that lacks require.main.filename, such as a jest test runner, // startDir is already process.cwd(), and should not be shortened. // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. if (!rootPath && this.#shim.path.extname(startDir)) { startDir = this.#shim.path.dirname(startDir); } const pkgJsonPath = this.#shim.findUp( startDir, (dir: string[], names: string[]) => { if (names.includes('package.json')) { return 'package.json'; } else { return undefined; } } ); assertNotStrictEqual(pkgJsonPath, undefined, this.#shim); obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8')); // eslint-disable-next-line no-empty } catch (_noop) {} this.#pkgs[npath] = obj || {}; return this.#pkgs[npath]; } [kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>( type: T, keys: string | string[] ) { keys = ([] as string[]).concat(keys); keys.forEach(key => { key = this[kSanitizeKey](key); this.#options[type].push(key); }); } [kPopulateParserHintSingleValueDictionary]< T extends | Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>> | 'default', K extends keyof Options[T] & string = keyof Options[T] & string, V extends ValueOf<Options[T]> = ValueOf<Options[T]> >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value?: V ) { this[kPopulateParserHintDictionary]<T, K, V>( builder, type, key, value, (type, key, value) => { this.#options[type][key] = value as ValueOf<Options[T]>; } ); } [kPopulateParserHintArrayDictionary]< T extends DictionaryKeyof<Options, any[]>, K extends keyof Options[T] & string = keyof Options[T] & string, V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] = | ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value?: V ) { this[kPopulateParserHintDictionary]<T, K, V>( builder, type, key, value, (type, key, value) => { this.#options[type][key] = ( this.#options[type][key] || ([] as Options[T][keyof Options[T]]) ).concat(value); } ); } [kPopulateParserHintDictionary]< T extends keyof Options, K extends keyof Options[T], V >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value: V | undefined, singleKeyHandler: (type: T, key: K, value?: V) => void ) { if (Array.isArray(key)) { // an array of keys with one value ['x', 'y', 'z'], function parse () {} key.forEach(k => { builder(k, value!); }); } else if ( ((key): key is {[key in K]: V} => typeof key === 'object')(key) ) { // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} for (const k of objectKeys(key)) { builder(k, key[k]); } } else { singleKeyHandler(type, this[kSanitizeKey](key), value); } } [kSanitizeKey](key: any) { if (key === '__proto__') return '___proto___'; return key; } [kSetKey]( key: string | string[] | Dictionary<string | boolean>, set?: boolean | string ) { this[kPopulateParserHintSingleValueDictionary]( this[kSetKey].bind(this), 'key', key, set ); return this; } [kUnfreeze]() { const frozen = this.#frozens.pop(); assertNotStrictEqual(frozen, undefined, this.#shim); let configObjects: Dictionary[]; ({ options: this.#options, configObjects, exitProcess: this.#exitProcess, groups: this.#groups, output: this.#output, exitError: this.#exitError, hasOutput: this.#hasOutput, parsed: this.parsed, strict: this.#strict, strictCommands: this.#strictCommands, strictOptions: this.#strictOptions, completionCommand: this.#completionCommand, parseFn: this.#parseFn, parseContext: this.#parseContext, } = frozen); this.#options.configObjects = configObjects; this.#usage.unfreeze(); this.#validation.unfreeze(); this.#command.unfreeze(); this.#globalMiddleware.unfreeze(); } // If argv is a promise (which is possible if async middleware is used) // delay applying validation until the promise has resolved: [kValidateAsync]( validation: (argv: Arguments) => void, argv: Arguments | Promise<Arguments> ): Arguments | Promise<Arguments> { return maybeAsyncResult<Arguments>(argv, result => { validation(result); return result; }); } // Note: these method names could change at any time, and should not be // depended upon externally: getInternalMethods(): YargsInternalMethods { return { getCommandInstance: this[kGetCommandInstance].bind(this), getContext: this[kGetContext].bind(this), getHasOutput: this[kGetHasOutput].bind(this), getLoggerInstance: this[kGetLoggerInstance].bind(this), getParseContext: this[kGetParseContext].bind(this), getParserConfiguration: this[kGetParserConfiguration].bind(this), getUsageConfiguration: this[kGetUsageConfiguration].bind(this), getUsageInstance: this[kGetUsageInstance].bind(this), getValidationInstance: this[kGetValidationInstance].bind(this), hasParseCallback: this[kHasParseCallback].bind(this), isGlobalContext: this[kIsGlobalContext].bind(this), postProcess: this[kPostProcess].bind(this), reset: this[kReset].bind(this), runValidation: this[kRunValidation].bind(this), runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), setHasOutput: this[kSetHasOutput].bind(this), }; } [kGetCommandInstance](): CommandInstance { return this.#command; } [kGetContext](): Context { return this.#context; } [kGetHasOutput](): boolean { return this.#hasOutput; } [kGetLoggerInstance](): LoggerInstance { return this.#logger; } [kGetParseContext](): Object { return this.#parseContext || {}; } [kGetUsageInstance](): UsageInstance { return this.#usage; } [kGetValidationInstance](): ValidationInstance { return this.#validation; } [kHasParseCallback](): boolean { return !!this.#parseFn; } [kIsGlobalContext](): boolean { return this.#isGlobalContext; } [kPostProcess]<T extends Arguments | Promise<Arguments>>( argv: Arguments | Promise<Arguments>, populateDoubleDash: boolean, calledFromCommand: boolean, runGlobalMiddleware: boolean ): any { if (calledFromCommand) return argv; if (isPromise(argv)) return argv; if (!populateDoubleDash) { argv = this[kCopyDoubleDash](argv); } const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; if (parsePositionalNumbers) { argv = this[kParsePositionalNumbers](argv as Arguments); } if (runGlobalMiddleware) { argv = applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), false ); } return argv; } // put yargs back into an initial state; this is used mainly for running // commands in a breadth first manner: [kReset](aliases: Aliases = {}): YargsInstance { this.#options = this.#options || ({} as Options); const tmpOptions = {} as Options; tmpOptions.local = this.#options.local || []; tmpOptions.configObjects = this.#options.configObjects || []; // if a key has been explicitly set as local, // we should reset it before passing options to command. const localLookup: Dictionary<boolean> = {}; tmpOptions.local.forEach(l => { localLookup[l] = true; (aliases[l] || []).forEach(a => { localLookup[a] = true; }); }); // add all groups not set to local to preserved groups Object.assign( this.#preservedGroups, Object.keys(this.#groups).reduce((acc, groupName) => { const keys = this.#groups[groupName].filter( key => !(key in localLookup) ); if (keys.length > 0) { acc[groupName] = keys; } return acc; }, {} as Dictionary<string[]>) ); // groups can now be reset this.#groups = {}; const arrayOptions: KeyOf<Options, string[]>[] = [ 'array', 'boolean', 'string', 'skipValidation', 'count', 'normalize', 'number', 'hiddenOptions', ]; const objectOptions: DictionaryKeyof<Options>[] = [ 'narg', 'key', 'alias', 'default', 'defaultDescription', 'config', 'choices', 'demandedOptions', 'demandedCommands', 'deprecatedOptions', ]; arrayOptions.forEach(k => { tmpOptions[k] = (this.#options[k] || []).filter( (k: string) => !localLookup[k] ); }); objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => { tmpOptions[k] = objFilter( this.#options[k], k => !localLookup[k as string] ); }); tmpOptions.envPrefix = this.#options.envPrefix; this.#options = tmpOptions; // if this is the first time being executed, create // instances of all our helpers -- otherwise just reset. this.#usage = this.#usage ? this.#usage.reset(localLookup) : Usage(this, this.#shim); this.#validation = this.#validation ? this.#validation.reset(localLookup) : Validation(this, this.#usage, this.#shim); this.#command = this.#command ? this.#command.reset() : Command( this.#usage, this.#validation, this.#globalMiddleware, this.#shim ); if (!this.#completion) this.#completion = Completion( this, this.#usage, this.#command, this.#shim ); this.#globalMiddleware.reset(); this.#completionCommand = null; this.#output = ''; this.#exitError = null; this.#hasOutput = false; this.parsed = false; return this; } [kRebase](base: string, dir: string): string { return this.#shim.path.relative(base, dir); } [kRunYargsParserAndExecuteCommands]( args: string | string[] | null, shortCircuit?: boolean | null, calledFromCommand?: boolean, commandIndex = 0, helpOnly = false ): Arguments | Promise<Arguments> { let skipValidation = !!calledFromCommand || helpOnly; args = args || this.#processArgs; this.#options.__ = this.#shim.y18n.__; this.#options.configuration = this[kGetParserConfiguration](); const populateDoubleDash = !!this.#options.configuration['populate--']; const config = Object.assign({}, this.#options.configuration, { 'populate--': true, }); const parsed = this.#shim.Parser.detailed( args, Object.assign({}, this.#options, { configuration: {'parse-positional-numbers': false, ...config}, }) ) as DetailedArguments; const argv: Arguments = Object.assign( parsed.argv, this.#parseContext ) as Arguments; let argvPromise: Arguments | Promise<Arguments> | undefined = undefined; const aliases = parsed.aliases; let helpOptSet = false; let versionOptSet = false; Object.keys(argv).forEach(key => { if (key === this.#helpOpt && argv[key]) { helpOptSet = true; } else if (key === this.#versionOpt && argv[key]) { versionOptSet = true; } }); argv.$0 = this.$0; this.parsed = parsed; // A single yargs instance may be used multiple times, e.g. // const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo'). // When a prior parse has completed and a new parse is beginning, we // need to clear the cached help message from the previous parse: if (commandIndex === 0) { this.#usage.clearCachedHelpMessage(); } try { this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain. // while building up the argv object, there // are two passes through the parser. If completion // is being performed short-circuit on the first pass. if (shortCircuit) { return this[kPostProcess]( argv, populateDoubleDash, !!calledFromCommand, false // Don't run middleware when figuring out completion. ); } // if there's a handler associated with a // command defer processing to it. if (this.#helpOpt) { // consider any multi-char helpOpt alias as a valid help command // unless all helpOpt aliases are single-char // note that parsed.aliases is a normalized bidirectional map :) const helpCmds = [this.#helpOpt] .concat(aliases[this.#helpOpt] || []) .filter(k => k.length > 1); // check if help should trigger and strip it from _. if (helpCmds.includes('' + argv._[argv._.length - 1])) { argv._.pop(); helpOptSet = true; } } this.#isGlobalContext = false; const handlerKeys = this.#command.getCommands(); const requestCompletions = this.#completion!.completionKey in argv; const skipRecommendation = helpOptSet || requestCompletions || helpOnly; if (argv._.length) { if (handlerKeys.length) { let firstUnknownCommand; for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { cmd = String(argv._[i]); if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) { // commands are executed using a recursive algorithm that executes // the deepest command first; we keep track of the position in the // argv._ array that is currently being executed. const innerArgv = this.#command.runCommand( cmd, this, parsed, i + 1, // Don't run a handler, just figure out the help string: helpOnly, // Passed to builder so that expensive commands can be deferred: helpOptSet || versionOptSet || helpOnly ); return this[kPostProcess]( innerArgv, populateDoubleDash, !!calledFromCommand, false ); } else if ( !firstUnknownCommand && cmd !== this.#completionCommand ) { firstUnknownCommand = cmd; break; } } // recommend a command if recommendCommands() has // been enabled, and no commands were found to execute if ( !this.#command.hasDefaultCommand() && this.#recommendCommands && firstUnknownCommand && !skipRecommendation ) { this.#validation.recommendCommands( firstUnknownCommand, handlerKeys ); } } // generate a completion script for adding to ~/.bashrc. if ( this.#completionCommand && argv._.includes(this.#completionCommand) && !requestCompletions ) { if (this.#exitProcess) setBlocking(true); this.showCompletionScript(); this.exit(0); } } if (this.#command.hasDefaultCommand() && !skipRecommendation) { const innerArgv = this.#command.runCommand( null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly ); return this[kPostProcess]( innerArgv, populateDoubleDash, !!calledFromCommand, false ); } // we must run completions first, a user might // want to complete the --help or --version option. if (requestCompletions) { if (this.#exitProcess) setBlocking(true); // we allow for asynchronous completions, // e.g., loading in a list of commands from an API. args = ([] as string[]).concat(args); const completionArgs = args.slice( args.indexOf(`--${this.#completion!.completionKey}`) + 1 ); this.#completion!.getCompletion(completionArgs, (err, completions) => { if (err) throw new YError(err.message); (completions || []).forEach(completion => { this.#logger.log(completion); }); this.exit(0); }); return this[kPostProcess]( argv, !populateDoubleDash, !!calledFromCommand, false // Don't run middleware when figuring out completion. ); } // Handle 'help' and 'version' options // if we haven't already output help! if (!this.#hasOutput) { if (helpOptSet) { if (this.#exitProcess) setBlocking(true); skipValidation = true; this.showHelp('log'); this.exit(0); } else if (versionOptSet) { if (this.#exitProcess) setBlocking(true); skipValidation = true; this.#usage.showVersion('log'); this.exit(0); } } // Check if any of the options to skip validation were provided if (!skipValidation && this.#options.skipValidation.length > 0) { skipValidation = Object.keys(argv).some( key => this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true ); } // If the help or version options were used and exitProcess is false, // or if explicitly skipped, we won't run validations. if (!skipValidation) { if (parsed.error) throw new YError(parsed.error.message); // if we're executed via bash completion, don't // bother with validation. if (!requestCompletions) { const validation = this[kRunValidation](aliases, {}, parsed.error); if (!calledFromCommand) { argvPromise = applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), true ); } argvPromise = this[kValidateAsync](validation, argvPromise ?? argv); if (isPromise(argvPromise) && !calledFromCommand) { argvPromise = argvPromise.then(() => { return applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), false ); }); } } } } catch (err) { if (err instanceof YError) this.#usage.fail(err.message, err); else throw err; } return this[kPostProcess]( argvPromise ?? argv, populateDoubleDash, !!calledFromCommand, true ); } [kRunValidation]( aliases: Dictionary<string[]>, positionalMap: Dictionary<string[]>, parseErrors: Error | null, isDefaultCommand?: boolean ): (argv: Arguments) => void { const demandedOptions = {...this.getDemandedOptions()}; return (argv: Arguments) => { if (parseErrors) throw new YError(parseErrors.message); this.#validation.nonOptionCount(argv); this.#validation.requiredArguments(argv, demandedOptions); let failedStrictCommands = false; if (this.#strictCommands) { failedStrictCommands = this.#validation.unknownCommands(argv); } if (this.#strict && !failedStrictCommands) { this.#validation.unknownArguments( argv, aliases, positionalMap, !!isDefaultCommand ); } else if (this.#strictOptions) { this.#validation.unknownArguments(argv, aliases, {}, false, false); } this.#validation.limitedChoices(argv); this.#validation.implications(argv); this.#validation.conflicting(argv); }; } [kSetHasOutput]() { this.#hasOutput = true; } [kTrackManuallySetKeys](keys: string | string[]) { if (typeof keys === 'string') { this.#options.key[keys] = true; } else { for (const k of keys) { this.#options.key[k] = true; } } } }
2,901
( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,902
( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }
interface Arguments { /** The script name or node command */ $0: string; /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,903
( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,904
( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }
class YargsInstance { $0: string; argv?: Arguments; customScriptName = false; parsed: DetailedArguments | false = false; #command: CommandInstance; #cwd: string; // use context object to keep track of resets, subcommand execution, etc., // submodules should modify and check the state of context as necessary: #context: Context = {commands: [], fullCommands: []}; #completion: CompletionInstance | null = null; #completionCommand: string | null = null; #defaultShowHiddenOpt = 'show-hidden'; #exitError: YError | string | nil = null; #detectLocale = true; #emittedWarnings: Dictionary<boolean> = {}; #exitProcess = true; #frozens: FrozenYargsInstance[] = []; #globalMiddleware: GlobalMiddleware; #groups: Dictionary<string[]> = {}; #hasOutput = false; #helpOpt: string | null = null; #isGlobalContext = true; #logger: LoggerInstance; #output = ''; #options: Options; #parentRequire?: RequireType; #parserConfig: Configuration = {}; #parseFn: ParseCallback | null = null; #parseContext: object | null = null; #pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {}; #preservedGroups: Dictionary<string[]> = {}; #processArgs: string | string[]; #recommendCommands = false; #shim: PlatformShim; #strict = false; #strictCommands = false; #strictOptions = false; #usage: UsageInstance; #usageConfig: UsageConfiguration = {}; #versionOpt: string | null = null; #validation: ValidationInstance; constructor( processArgs: string | string[] = [], cwd: string, parentRequire: RequireType | undefined, shim: PlatformShim ) { this.#shim = shim; this.#processArgs = processArgs; this.#cwd = cwd; this.#parentRequire = parentRequire; this.#globalMiddleware = new GlobalMiddleware(this); this.$0 = this[kGetDollarZero](); // #command, #validation, and #usage are initialized on first reset: this[kReset](); this.#command = this!.#command; this.#usage = this!.#usage; this.#validation = this!.#validation; this.#options = this!.#options; this.#options.showHiddenOpt = this.#defaultShowHiddenOpt; this.#logger = this[kCreateLogger](); } addHelpOpt(opt?: string | false, msg?: string): YargsInstance { const defaultHelpOpt = 'help'; argsert('[string|boolean] [string]', [opt, msg], arguments.length); // nuke the key previously configured // to return help. if (this.#helpOpt) { this[kDeleteFromParserHintObject](this.#helpOpt); this.#helpOpt = null; } if (opt === false && msg === undefined) return this; // use arguments, fallback to defaults for opt and msg this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt; this.boolean(this.#helpOpt); this.describe( this.#helpOpt, msg || this.#usage.deferY18nLookup('Show help') ); return this; } help(opt?: string, msg?: string): YargsInstance { return this.addHelpOpt(opt, msg); } addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance { argsert('[string|boolean] [string]', [opt, msg], arguments.length); if (opt === false && msg === undefined) return this; const showHiddenOpt = typeof opt === 'string' ? opt : this.#defaultShowHiddenOpt; this.boolean(showHiddenOpt); this.describe( showHiddenOpt, msg || this.#usage.deferY18nLookup('Show hidden options') ); this.#options.showHiddenOpt = showHiddenOpt; return this; } showHidden(opt?: string | false, msg?: string): YargsInstance { return this.addShowHiddenOpt(opt, msg); } alias( key: string | string[] | Dictionary<string | string[]>, value?: string | string[] ): YargsInstance { argsert( '<object|string|array> [string|array]', [key, value], arguments.length ); this[kPopulateParserHintArrayDictionary]( this.alias.bind(this), 'alias', key, value ); return this; } array(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('array', keys); this[kTrackManuallySetKeys](keys); return this; } boolean(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('boolean', keys); this[kTrackManuallySetKeys](keys); return this; } check( f: (argv: Arguments, options: Options) => any, global?: boolean ): YargsInstance { argsert('<function> [boolean]', [f, global], arguments.length); this.middleware( ( argv: Arguments, _yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { return f(argv, _yargs.getOptions()); }, (result: any): Partial<Arguments> | Promise<Partial<Arguments>> => { if (!result) { this.#usage.fail( this.#shim.y18n.__('Argument check failed: %s', f.toString()) ); } else if (typeof result === 'string' || result instanceof Error) { this.#usage.fail(result.toString(), result); } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { this.#usage.fail(err.message ? err.message : err.toString(), err); return argv; } ); }, false, global ); return this; } choices( key: string | string[] | Dictionary<string | string[]>, value?: string | string[] ): YargsInstance { argsert( '<object|string|array> [string|array]', [key, value], arguments.length ); this[kPopulateParserHintArrayDictionary]( this.choices.bind(this), 'choices', key, value ); return this; } coerce( keys: string | string[] | Dictionary<CoerceCallback>, value?: CoerceCallback ): YargsInstance { argsert( '<object|string|array> [function]', [keys, value], arguments.length ); if (Array.isArray(keys)) { if (!value) { throw new YError('coerce callback must be provided'); } for (const key of keys) { this.coerce(key, value); } return this; } else if (typeof keys === 'object') { for (const key of Object.keys(keys)) { this.coerce(key, keys[key]); } return this; } if (!value) { throw new YError('coerce callback must be provided'); } // This noop tells yargs-parser about the existence of the option // represented by "keys", so that it can apply camel case expansion // if needed: this.#options.key[keys] = true; this.#globalMiddleware.addCoerceMiddleware( ( argv: Arguments, yargs: YargsInstance ): Partial<Arguments> | Promise<Partial<Arguments>> => { let aliases: Dictionary<string[]>; // Skip coerce logic if related arg was not provided const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); if (!shouldCoerce) { return argv; } return maybeAsyncResult< Partial<Arguments> | Promise<Partial<Arguments>> | any >( () => { aliases = yargs.getAliases(); return value(argv[keys]); }, (result: any): Partial<Arguments> => { argv[keys] = result; const stripAliased = yargs .getInternalMethods() .getParserConfiguration()['strip-aliased']; if (aliases[keys] && stripAliased !== true) { for (const alias of aliases[keys]) { argv[alias] = result; } } return argv; }, (err: Error): Partial<Arguments> | Promise<Partial<Arguments>> => { throw new YError(err.message); } ); }, keys ); return this; } conflicts( key1: string | Dictionary<string | string[]>, key2?: string | string[] ): YargsInstance { argsert('<string|object> [string|array]', [key1, key2], arguments.length); this.#validation.conflicts(key1, key2); return this; } config( key: string | string[] | Dictionary = 'config', msg?: string | ConfigCallback, parseFn?: ConfigCallback ): YargsInstance { argsert( '[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length ); // allow a config object to be provided directly. if (typeof key === 'object' && !Array.isArray(key)) { key = applyExtends( key, this.#cwd, this[kGetParserConfiguration]()['deep-merge-config'] || false, this.#shim ); this.#options.configObjects = (this.#options.configObjects || []).concat( key ); return this; } // allow for a custom parsing function. if (typeof msg === 'function') { parseFn = msg; msg = undefined; } this.describe( key, msg || this.#usage.deferY18nLookup('Path to JSON config file') ); (Array.isArray(key) ? key : [key]).forEach(k => { this.#options.config[k] = parseFn || true; }); return this; } completion( cmd?: string, desc?: string | false | CompletionFunction, fn?: CompletionFunction ): YargsInstance { argsert( '[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length ); // a function to execute when generating // completions can be provided as the second // or third argument to completion. if (typeof desc === 'function') { fn = desc; desc = undefined; } // register the completion command. this.#completionCommand = cmd || this.#completionCommand || 'completion'; if (!desc && desc !== false) { desc = 'generate completion script'; } this.command(this.#completionCommand, desc); // a function can be provided if (fn) this.#completion!.registerFunction(fn); return this; } command( cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[], description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, middlewares?: Middleware[], deprecated?: boolean ): YargsInstance { argsert( '<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length ); this.#command.addHandler( cmd, description, builder, handler, middlewares, deprecated ); return this; } commands( cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[], description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, middlewares?: Middleware[], deprecated?: boolean ): YargsInstance { return this.command( cmd, description, builder, handler, middlewares, deprecated ); } commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance { argsert('<string> [object]', [dir, opts], arguments.length); const req = this.#parentRequire || this.#shim.require; this.#command.addDirectory(dir, req, this.#shim.getCallerFile(), opts); return this; } count(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('count', keys); this[kTrackManuallySetKeys](keys); return this; } default( key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string ): YargsInstance { argsert( '<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length ); if (defaultDescription) { assertSingleKey(key, this.#shim); this.#options.defaultDescription[key] = defaultDescription; } if (typeof value === 'function') { assertSingleKey(key, this.#shim); if (!this.#options.defaultDescription[key]) this.#options.defaultDescription[key] = this.#usage.functionDescription(value); value = value.call(); } this[kPopulateParserHintSingleValueDictionary]<'default'>( this.default.bind(this), 'default', key, value ); return this; } defaults( key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string ): YargsInstance { return this.default(key, value, defaultDescription); } demandCommand( min = 1, max?: number | string, minMsg?: string | null, maxMsg?: string | null ): YargsInstance { argsert( '[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length ); if (typeof max !== 'number') { minMsg = max; max = Infinity; } this.global('_', false); this.#options.demandedCommands._ = { min, max, minMsg, maxMsg, }; return this; } demand( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { // you can optionally provide a 'max' key, // which will raise an exception if too many '_' // options are provided. if (Array.isArray(max)) { max.forEach(key => { assertNotStrictEqual(msg, true as const, this.#shim); this.demandOption(key, msg); }); max = Infinity; } else if (typeof max !== 'number') { msg = max; max = Infinity; } if (typeof keys === 'number') { assertNotStrictEqual(msg, true as const, this.#shim); this.demandCommand(keys, max, msg, msg); } else if (Array.isArray(keys)) { keys.forEach(key => { assertNotStrictEqual(msg, true as const, this.#shim); this.demandOption(key, msg); }); } else { if (typeof msg === 'string') { this.demandOption(keys, msg); } else if (msg === true || typeof msg === 'undefined') { this.demandOption(keys); } } return this; } demandOption( keys: string | string[] | Dictionary<string | undefined>, msg?: string ): YargsInstance { argsert('<object|string|array> [string]', [keys, msg], arguments.length); this[kPopulateParserHintSingleValueDictionary]( this.demandOption.bind(this), 'demandedOptions', keys, msg ); return this; } deprecateOption(option: string, message: string | boolean): YargsInstance { argsert('<string> [string|boolean]', [option, message], arguments.length); this.#options.deprecatedOptions[option] = message; return this; } describe( keys: string | string[] | Dictionary<string>, description?: string ): YargsInstance { argsert( '<object|string|array> [string]', [keys, description], arguments.length ); this[kSetKey](keys, true); this.#usage.describe(keys, description); return this; } detectLocale(detect: boolean): YargsInstance { argsert('<boolean>', [detect], arguments.length); this.#detectLocale = detect; return this; } // as long as options.envPrefix is not undefined, // parser will apply env vars matching prefix to argv env(prefix?: string | false): YargsInstance { argsert('[string|boolean]', [prefix], arguments.length); if (prefix === false) delete this.#options.envPrefix; else this.#options.envPrefix = prefix || ''; return this; } epilogue(msg: string): YargsInstance { argsert('<string>', [msg], arguments.length); this.#usage.epilog(msg); return this; } epilog(msg: string): YargsInstance { return this.epilogue(msg); } example( cmd: string | [string, string?][], description?: string ): YargsInstance { argsert('<string|array> [string]', [cmd, description], arguments.length); if (Array.isArray(cmd)) { cmd.forEach(exampleParams => this.example(...exampleParams)); } else { this.#usage.example(cmd, description); } return this; } // maybe exit, always capture context about why we wanted to exit: exit(code: number, err?: YError | string): void { this.#hasOutput = true; this.#exitError = err; if (this.#exitProcess) this.#shim.process.exit(code); } exitProcess(enabled = true): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#exitProcess = enabled; return this; } fail(f: FailureFunction | boolean): YargsInstance { argsert('<function|boolean>', [f], arguments.length); if (typeof f === 'boolean' && f !== false) { throw new YError( "Invalid first argument. Expected function or boolean 'false'" ); } this.#usage.failFn(f); return this; } getAliases(): Dictionary<string[]> { return this.parsed ? this.parsed.aliases : {}; } async getCompletion( args: string[], done?: (err: Error | null, completions: string[] | undefined) => void ): Promise<string[] | void> { argsert('<array> [function]', [args, done], arguments.length); if (!done) { return new Promise((resolve, reject) => { this.#completion!.getCompletion(args, (err, completions) => { if (err) reject(err); else resolve(completions); }); }); } else { return this.#completion!.getCompletion(args, done); } } getDemandedOptions() { argsert([], 0); return this.#options.demandedOptions; } getDemandedCommands() { argsert([], 0); return this.#options.demandedCommands; } getDeprecatedOptions() { argsert([], 0); return this.#options.deprecatedOptions; } getDetectLocale(): boolean { return this.#detectLocale; } getExitProcess(): boolean { return this.#exitProcess; } // combine explicit and preserved groups. explicit groups should be first getGroups(): Dictionary<string[]> { return Object.assign({}, this.#groups, this.#preservedGroups); } getHelp(): Promise<string> { this.#hasOutput = true; if (!this.#usage.hasCachedHelpMessage()) { if (!this.parsed) { // Run the parser as if --help was passed to it (this is what // the last parameter `true` indicates). const parse = this[kRunYargsParserAndExecuteCommands]( this.#processArgs, undefined, undefined, 0, true ); if (isPromise(parse)) { return parse.then(() => { return this.#usage.help(); }); } } // Ensure top level options/positionals have been configured: const builderResponse = this.#command.runDefaultBuilderOn(this); if (isPromise(builderResponse)) { return builderResponse.then(() => { return this.#usage.help(); }); } } return Promise.resolve(this.#usage.help()); } getOptions(): Options { return this.#options; } getStrict(): boolean { return this.#strict; } getStrictCommands(): boolean { return this.#strictCommands; } getStrictOptions(): boolean { return this.#strictOptions; } global(globals: string | string[], global?: boolean): YargsInstance { argsert('<string|array> [boolean]', [globals, global], arguments.length); globals = ([] as string[]).concat(globals); if (global !== false) { this.#options.local = this.#options.local.filter( l => globals.indexOf(l) === -1 ); } else { globals.forEach(g => { if (!this.#options.local.includes(g)) this.#options.local.push(g); }); } return this; } group(opts: string | string[], groupName: string): YargsInstance { argsert('<string|array> <string>', [opts, groupName], arguments.length); const existing = this.#preservedGroups[groupName] || this.#groups[groupName]; if (this.#preservedGroups[groupName]) { // we now only need to track this group name in groups. delete this.#preservedGroups[groupName]; } const seen: Dictionary<boolean> = {}; this.#groups[groupName] = (existing || []).concat(opts).filter(key => { if (seen[key]) return false; return (seen[key] = true); }); return this; } hide(key: string): YargsInstance { argsert('<string>', [key], arguments.length); this.#options.hiddenOptions.push(key); return this; } implies( key: string | Dictionary<KeyOrPos | KeyOrPos[]>, value?: KeyOrPos | KeyOrPos[] ): YargsInstance { argsert( '<string|object> [number|string|array]', [key, value], arguments.length ); this.#validation.implies(key, value); return this; } locale(locale?: string): YargsInstance | string { argsert('[string]', [locale], arguments.length); if (locale === undefined) { this[kGuessLocale](); return this.#shim.y18n.getLocale(); } this.#detectLocale = false; this.#shim.y18n.setLocale(locale); return this; } middleware( callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean, global?: boolean ): YargsInstance { return this.#globalMiddleware.addMiddleware( callback, !!applyBeforeValidation, global ); } nargs( key: string | string[] | Dictionary<number>, value?: number ): YargsInstance { argsert('<string|object|array> [number]', [key, value], arguments.length); this[kPopulateParserHintSingleValueDictionary]( this.nargs.bind(this), 'narg', key, value ); return this; } normalize(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('normalize', keys); return this; } number(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('number', keys); this[kTrackManuallySetKeys](keys); return this; } option( key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition ): YargsInstance { argsert('<string|object> [object]', [key, opt], arguments.length); if (typeof key === 'object') { Object.keys(key).forEach(k => { this.options(k, key[k]); }); } else { if (typeof opt !== 'object') { opt = {}; } this[kTrackManuallySetKeys](key); // Warn about version name collision // Addresses: https://github.com/yargs/yargs/issues/1979 if (this.#versionOpt && (key === 'version' || opt?.alias === 'version')) { this[kEmitWarning]( [ '"version" is a reserved word.', 'Please do one of the following:', '- Disable version with `yargs.version(false)` if using "version" as an option', '- Use the built-in `yargs.version` method instead (if applicable)', '- Use a different option key', 'https://yargs.js.org/docs/#api-reference-version', ].join('\n'), undefined, 'versionWarning' // TODO: better dedupeId ); } this.#options.key[key] = true; // track manually set keys. if (opt.alias) this.alias(key, opt.alias); const deprecate = opt.deprecate || opt.deprecated; if (deprecate) { this.deprecateOption(key, deprecate); } const demand = opt.demand || opt.required || opt.require; // A required option can be specified via "demand: true". if (demand) { this.demand(key, demand); } if (opt.demandOption) { this.demandOption( key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined ); } if (opt.conflicts) { this.conflicts(key, opt.conflicts); } if ('default' in opt) { this.default(key, opt.default); } if (opt.implies !== undefined) { this.implies(key, opt.implies); } if (opt.nargs !== undefined) { this.nargs(key, opt.nargs); } if (opt.config) { this.config(key, opt.configParser); } if (opt.normalize) { this.normalize(key); } if (opt.choices) { this.choices(key, opt.choices); } if (opt.coerce) { this.coerce(key, opt.coerce); } if (opt.group) { this.group(key, opt.group); } if (opt.boolean || opt.type === 'boolean') { this.boolean(key); if (opt.alias) this.boolean(opt.alias); } if (opt.array || opt.type === 'array') { this.array(key); if (opt.alias) this.array(opt.alias); } if (opt.number || opt.type === 'number') { this.number(key); if (opt.alias) this.number(opt.alias); } if (opt.string || opt.type === 'string') { this.string(key); if (opt.alias) this.string(opt.alias); } if (opt.count || opt.type === 'count') { this.count(key); } if (typeof opt.global === 'boolean') { this.global(key, opt.global); } if (opt.defaultDescription) { this.#options.defaultDescription[key] = opt.defaultDescription; } if (opt.skipValidation) { this.skipValidation(key); } const desc = opt.describe || opt.description || opt.desc; const descriptions = this.#usage.getDescriptions(); if ( !Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc === 'string' ) { this.describe(key, desc); } if (opt.hidden) { this.hide(key); } if (opt.requiresArg) { this.requiresArg(key); } } return this; } options( key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition ): YargsInstance { return this.option(key, opt); } parse( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Arguments | Promise<Arguments> { argsert( '[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length ); this[kFreeze](); // Push current state of parser onto stack. if (typeof args === 'undefined') { args = this.#processArgs; } // a context object can optionally be provided, this allows // additional information to be passed to a command handler. if (typeof shortCircuit === 'object') { this.#parseContext = shortCircuit; shortCircuit = _parseFn; } // by providing a function as a second argument to // parse you can capture output that would otherwise // default to printing to stdout/stderr. if (typeof shortCircuit === 'function') { this.#parseFn = shortCircuit as ParseCallback; shortCircuit = false; } // completion short-circuits the parsing process, // skipping validation, etc. if (!shortCircuit) this.#processArgs = args; if (this.#parseFn) this.#exitProcess = false; const parsed = this[kRunYargsParserAndExecuteCommands]( args, !!shortCircuit ); const tmpParsed = this.parsed; this.#completion!.setParsed(this.parsed as DetailedArguments); if (isPromise(parsed)) { return parsed .then(argv => { if (this.#parseFn) this.#parseFn(this.#exitError, argv, this.#output); return argv; }) .catch(err => { if (this.#parseFn) { this.#parseFn!( err, (this.parsed as DetailedArguments).argv, this.#output ); } throw err; }) .finally(() => { this[kUnfreeze](); // Pop the stack. this.parsed = tmpParsed; }); } else { if (this.#parseFn) this.#parseFn(this.#exitError, parsed, this.#output); this[kUnfreeze](); // Pop the stack. this.parsed = tmpParsed; } return parsed; } parseAsync( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Promise<Arguments> { const maybePromise = this.parse(args, shortCircuit, _parseFn); return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise; } parseSync( args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback ): Arguments { const maybePromise = this.parse(args, shortCircuit, _parseFn); if (isPromise(maybePromise)) { throw new YError( '.parseSync() must not be used with asynchronous builders, handlers, or middleware' ); } return maybePromise; } parserConfiguration(config: Configuration) { argsert('<object>', [config], arguments.length); this.#parserConfig = config; return this; } pkgConf(key: string, rootPath?: string): YargsInstance { argsert('<string> [string]', [key, rootPath], arguments.length); let conf = null; // prefer cwd to require-main-filename in this method // since we're looking for e.g. "nyc" config in nyc consumer // rather than "yargs" config in nyc (where nyc is the main filename) const obj = this[kPkgUp](rootPath || this.#cwd); // If an object exists in the key, add it to options.configObjects if (obj[key] && typeof obj[key] === 'object') { conf = applyExtends( obj[key] as {[key: string]: string}, rootPath || this.#cwd, this[kGetParserConfiguration]()['deep-merge-config'] || false, this.#shim ); this.#options.configObjects = (this.#options.configObjects || []).concat( conf ); } return this; } positional(key: string, opts: PositionalDefinition): YargsInstance { argsert('<string> <object>', [key, opts], arguments.length); // .positional() only supports a subset of the configuration // options available to .option(): const supportedOpts: (keyof PositionalDefinition)[] = [ 'default', 'defaultDescription', 'implies', 'normalize', 'choices', 'conflicts', 'coerce', 'type', 'describe', 'desc', 'description', 'alias', ]; opts = objFilter(opts, (k, v) => { // type can be one of string|number|boolean. if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) return false; return supportedOpts.includes(k); }); // copy over any settings that can be inferred from the command string. const fullCommand = this.#context.fullCommands[this.#context.fullCommands.length - 1]; const parseOptions = fullCommand ? this.#command.cmdToParseOptions(fullCommand) : { array: [], alias: {}, default: {}, demand: {}, }; objectKeys(parseOptions).forEach(pk => { const parseOption = parseOptions[pk]; if (Array.isArray(parseOption)) { if (parseOption.indexOf(key) !== -1) opts[pk] = true; } else { if (parseOption[key] && !(pk in opts)) opts[pk] = parseOption[key]; } }); this.group(key, this.#usage.getPositionalGroupName()); return this.option(key, opts); } recommendCommands(recommend = true): YargsInstance { argsert('[boolean]', [recommend], arguments.length); this.#recommendCommands = recommend; return this; } required( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { return this.demand(keys, max, msg); } require( keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true ): YargsInstance { return this.demand(keys, max, msg); } requiresArg(keys: string | string[] | Dictionary): YargsInstance { // the 2nd paramter [number] in the argsert the assertion is mandatory // as populateParserHintSingleValueDictionary recursively calls requiresArg // with Nan as a 2nd parameter, although we ignore it argsert('<array|string|object> [number]', [keys], arguments.length); // If someone configures nargs at the same time as requiresArg, // nargs should take precedence, // see: https://github.com/yargs/yargs/pull/1572 // TODO: make this work with aliases, using a check similar to // checkAllAliases() in yargs-parser. if (typeof keys === 'string' && this.#options.narg[keys]) { return this; } else { this[kPopulateParserHintSingleValueDictionary]( this.requiresArg.bind(this), 'narg', keys, NaN ); } return this; } showCompletionScript($0?: string, cmd?: string): YargsInstance { argsert('[string] [string]', [$0, cmd], arguments.length); $0 = $0 || this.$0; this.#logger.log( this.#completion!.generateCompletionScript( $0, cmd || this.#completionCommand || 'completion' ) ); return this; } showHelp( level: 'error' | 'log' | ((message: string) => void) ): YargsInstance { argsert('[string|function]', [level], arguments.length); this.#hasOutput = true; if (!this.#usage.hasCachedHelpMessage()) { if (!this.parsed) { // Run the parser as if --help was passed to it (this is what // the last parameter `true` indicates). const parse = this[kRunYargsParserAndExecuteCommands]( this.#processArgs, undefined, undefined, 0, true ); if (isPromise(parse)) { parse.then(() => { this.#usage.showHelp(level); }); return this; } } // Ensure top level options/positionals have been configured: const builderResponse = this.#command.runDefaultBuilderOn(this); if (isPromise(builderResponse)) { builderResponse.then(() => { this.#usage.showHelp(level); }); return this; } } this.#usage.showHelp(level); return this; } scriptName(scriptName: string): YargsInstance { this.customScriptName = true; this.$0 = scriptName; return this; } showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance { argsert('[boolean|string] [string]', [enabled, message], arguments.length); this.#usage.showHelpOnFail(enabled, message); return this; } showVersion( level: 'error' | 'log' | ((message: string) => void) ): YargsInstance { argsert('[string|function]', [level], arguments.length); this.#usage.showVersion(level); return this; } skipValidation(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('skipValidation', keys); return this; } strict(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strict = enabled !== false; return this; } strictCommands(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strictCommands = enabled !== false; return this; } strictOptions(enabled?: boolean): YargsInstance { argsert('[boolean]', [enabled], arguments.length); this.#strictOptions = enabled !== false; return this; } string(keys: string | string[]): YargsInstance { argsert('<array|string>', [keys], arguments.length); this[kPopulateParserHintArray]('string', keys); this[kTrackManuallySetKeys](keys); return this; } terminalWidth(): number | null { argsert([], 0); return this.#shim.process.stdColumns; } updateLocale(obj: Dictionary<string>): YargsInstance { return this.updateStrings(obj); } updateStrings(obj: Dictionary<string>): YargsInstance { argsert('<object>', [obj], arguments.length); this.#detectLocale = false; this.#shim.y18n.updateLocale(obj); return this; } usage( msg: string | null, description?: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback ): YargsInstance { argsert( '<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length ); if (description !== undefined) { assertNotStrictEqual(msg, null, this.#shim); // .usage() can be used as an alias for defining // a default command. if ((msg || '').match(/^\$0( |$)/)) { return this.command(msg, description, builder, handler); } else { throw new YError( '.usage() description must start with $0 if being used as alias for .command()' ); } } else { this.#usage.usage(msg); return this; } } usageConfiguration(config: UsageConfiguration) { argsert('<object>', [config], arguments.length); this.#usageConfig = config; return this; } version(opt?: string | false, msg?: string, ver?: string): YargsInstance { const defaultVersionOpt = 'version'; argsert( '[boolean|string] [string] [string]', [opt, msg, ver], arguments.length ); // nuke the key previously configured // to return version #. if (this.#versionOpt) { this[kDeleteFromParserHintObject](this.#versionOpt); this.#usage.version(undefined); this.#versionOpt = null; } if (arguments.length === 0) { ver = this[kGuessVersion](); opt = defaultVersionOpt; } else if (arguments.length === 1) { if (opt === false) { // disable default 'version' key. return this; } ver = opt; opt = defaultVersionOpt; } else if (arguments.length === 2) { ver = msg; msg = undefined; } this.#versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt; msg = msg || this.#usage.deferY18nLookup('Show version number'); this.#usage.version(ver || undefined); this.boolean(this.#versionOpt); this.describe(this.#versionOpt, msg); return this; } wrap(cols: number | nil): YargsInstance { argsert('<number|null|undefined>', [cols], arguments.length); this.#usage.wrap(cols); return this; } // to simplify the parsing of positionals in commands, // we temporarily populate '--' rather than _, with arguments // after the '--' directive. After the parse, we copy these back. [kCopyDoubleDash](argv: Arguments): any { if (!argv._ || !argv['--']) return argv; // eslint-disable-next-line prefer-spread argv._.push.apply(argv._, argv['--']); // We catch an error here, in case someone has called Object.seal() // on the parsed object, see: https://github.com/babel/babel/pull/10733 try { delete argv['--']; // eslint-disable-next-line no-empty } catch (_err) {} return argv; } [kCreateLogger](): LoggerInstance { return { log: (...args: any[]) => { if (!this[kHasParseCallback]()) console.log(...args); this.#hasOutput = true; if (this.#output.length) this.#output += '\n'; this.#output += args.join(' '); }, error: (...args: any[]) => { if (!this[kHasParseCallback]()) console.error(...args); this.#hasOutput = true; if (this.#output.length) this.#output += '\n'; this.#output += args.join(' '); }, }; } [kDeleteFromParserHintObject](optionKey: string) { // delete from all parsing hints: // boolean, array, key, alias, etc. objectKeys(this.#options).forEach((hintKey: keyof Options) => { // configObjects is not a parsing hint array if (((key): key is 'configObjects' => key === 'configObjects')(hintKey)) return; const hint = this.#options[hintKey]; if (Array.isArray(hint)) { if (hint.includes(optionKey)) hint.splice(hint.indexOf(optionKey), 1); } else if (typeof hint === 'object') { delete (hint as Dictionary)[optionKey]; } }); // now delete the description from usage.js. delete this.#usage.getDescriptions()[optionKey]; } [kEmitWarning]( warning: string, type: string | undefined, deduplicationId: string ) { // prevent duplicate warning emissions if (!this.#emittedWarnings[deduplicationId]) { this.#shim.process.emitWarning(warning, type); this.#emittedWarnings[deduplicationId] = true; } } [kFreeze]() { this.#frozens.push({ options: this.#options, configObjects: this.#options.configObjects.slice(0), exitProcess: this.#exitProcess, groups: this.#groups, strict: this.#strict, strictCommands: this.#strictCommands, strictOptions: this.#strictOptions, completionCommand: this.#completionCommand, output: this.#output, exitError: this.#exitError!, hasOutput: this.#hasOutput, parsed: this.parsed, parseFn: this.#parseFn!, parseContext: this.#parseContext, }); this.#usage.freeze(); this.#validation.freeze(); this.#command.freeze(); this.#globalMiddleware.freeze(); } [kGetDollarZero](): string { let $0 = ''; // ignore the node bin, specify this in your // bin file with #!/usr/bin/env node let default$0: string[]; if (/\b(node|iojs|electron)(\.exe)?$/.test(this.#shim.process.argv()[0])) { default$0 = this.#shim.process.argv().slice(1, 2); } else { default$0 = this.#shim.process.argv().slice(0, 1); } $0 = default$0 .map(x => { const b = this[kRebase](this.#cwd, x); return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; }) .join(' ') .trim(); if ( this.#shim.getEnv('_') && this.#shim.getProcessArgvBin() === this.#shim.getEnv('_') ) { $0 = this.#shim .getEnv('_')! .replace( `${this.#shim.path.dirname(this.#shim.process.execPath())}/`, '' ); } return $0; } [kGetParserConfiguration](): Configuration { return this.#parserConfig; } [kGetUsageConfiguration](): UsageConfiguration { return this.#usageConfig; } [kGuessLocale]() { if (!this.#detectLocale) return; const locale = this.#shim.getEnv('LC_ALL') || this.#shim.getEnv('LC_MESSAGES') || this.#shim.getEnv('LANG') || this.#shim.getEnv('LANGUAGE') || 'en_US'; this.locale(locale.replace(/[.:].*/, '')); } [kGuessVersion](): string { const obj = this[kPkgUp](); return (obj.version as string) || 'unknown'; } // We wait to coerce numbers for positionals until after the initial parse. // This allows commands to configure number parsing on a positional by // positional basis: [kParsePositionalNumbers](argv: Arguments): any { const args: (string | number)[] = argv['--'] ? argv['--'] : argv._; for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { if ( this.#shim.Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`))) ) { args[i] = Number(arg); } } return argv; } [kPkgUp](rootPath?: string) { const npath = rootPath || '*'; if (this.#pkgs[npath]) return this.#pkgs[npath]; let obj = {}; try { let startDir = rootPath || this.#shim.mainFilename; // When called in an environment that lacks require.main.filename, such as a jest test runner, // startDir is already process.cwd(), and should not be shortened. // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. if (!rootPath && this.#shim.path.extname(startDir)) { startDir = this.#shim.path.dirname(startDir); } const pkgJsonPath = this.#shim.findUp( startDir, (dir: string[], names: string[]) => { if (names.includes('package.json')) { return 'package.json'; } else { return undefined; } } ); assertNotStrictEqual(pkgJsonPath, undefined, this.#shim); obj = JSON.parse(this.#shim.readFileSync(pkgJsonPath, 'utf8')); // eslint-disable-next-line no-empty } catch (_noop) {} this.#pkgs[npath] = obj || {}; return this.#pkgs[npath]; } [kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>( type: T, keys: string | string[] ) { keys = ([] as string[]).concat(keys); keys.forEach(key => { key = this[kSanitizeKey](key); this.#options[type].push(key); }); } [kPopulateParserHintSingleValueDictionary]< T extends | Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>> | 'default', K extends keyof Options[T] & string = keyof Options[T] & string, V extends ValueOf<Options[T]> = ValueOf<Options[T]> >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value?: V ) { this[kPopulateParserHintDictionary]<T, K, V>( builder, type, key, value, (type, key, value) => { this.#options[type][key] = value as ValueOf<Options[T]>; } ); } [kPopulateParserHintArrayDictionary]< T extends DictionaryKeyof<Options, any[]>, K extends keyof Options[T] & string = keyof Options[T] & string, V extends ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] = | ValueOf<ValueOf<Options[T]>> | ValueOf<ValueOf<Options[T]>>[] >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value?: V ) { this[kPopulateParserHintDictionary]<T, K, V>( builder, type, key, value, (type, key, value) => { this.#options[type][key] = ( this.#options[type][key] || ([] as Options[T][keyof Options[T]]) ).concat(value); } ); } [kPopulateParserHintDictionary]< T extends keyof Options, K extends keyof Options[T], V >( builder: (key: K, value: V, ...otherArgs: any[]) => YargsInstance, type: T, key: K | K[] | {[key in K]: V}, value: V | undefined, singleKeyHandler: (type: T, key: K, value?: V) => void ) { if (Array.isArray(key)) { // an array of keys with one value ['x', 'y', 'z'], function parse () {} key.forEach(k => { builder(k, value!); }); } else if ( ((key): key is {[key in K]: V} => typeof key === 'object')(key) ) { // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} for (const k of objectKeys(key)) { builder(k, key[k]); } } else { singleKeyHandler(type, this[kSanitizeKey](key), value); } } [kSanitizeKey](key: any) { if (key === '__proto__') return '___proto___'; return key; } [kSetKey]( key: string | string[] | Dictionary<string | boolean>, set?: boolean | string ) { this[kPopulateParserHintSingleValueDictionary]( this[kSetKey].bind(this), 'key', key, set ); return this; } [kUnfreeze]() { const frozen = this.#frozens.pop(); assertNotStrictEqual(frozen, undefined, this.#shim); let configObjects: Dictionary[]; ({ options: this.#options, configObjects, exitProcess: this.#exitProcess, groups: this.#groups, output: this.#output, exitError: this.#exitError, hasOutput: this.#hasOutput, parsed: this.parsed, strict: this.#strict, strictCommands: this.#strictCommands, strictOptions: this.#strictOptions, completionCommand: this.#completionCommand, parseFn: this.#parseFn, parseContext: this.#parseContext, } = frozen); this.#options.configObjects = configObjects; this.#usage.unfreeze(); this.#validation.unfreeze(); this.#command.unfreeze(); this.#globalMiddleware.unfreeze(); } // If argv is a promise (which is possible if async middleware is used) // delay applying validation until the promise has resolved: [kValidateAsync]( validation: (argv: Arguments) => void, argv: Arguments | Promise<Arguments> ): Arguments | Promise<Arguments> { return maybeAsyncResult<Arguments>(argv, result => { validation(result); return result; }); } // Note: these method names could change at any time, and should not be // depended upon externally: getInternalMethods(): YargsInternalMethods { return { getCommandInstance: this[kGetCommandInstance].bind(this), getContext: this[kGetContext].bind(this), getHasOutput: this[kGetHasOutput].bind(this), getLoggerInstance: this[kGetLoggerInstance].bind(this), getParseContext: this[kGetParseContext].bind(this), getParserConfiguration: this[kGetParserConfiguration].bind(this), getUsageConfiguration: this[kGetUsageConfiguration].bind(this), getUsageInstance: this[kGetUsageInstance].bind(this), getValidationInstance: this[kGetValidationInstance].bind(this), hasParseCallback: this[kHasParseCallback].bind(this), isGlobalContext: this[kIsGlobalContext].bind(this), postProcess: this[kPostProcess].bind(this), reset: this[kReset].bind(this), runValidation: this[kRunValidation].bind(this), runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), setHasOutput: this[kSetHasOutput].bind(this), }; } [kGetCommandInstance](): CommandInstance { return this.#command; } [kGetContext](): Context { return this.#context; } [kGetHasOutput](): boolean { return this.#hasOutput; } [kGetLoggerInstance](): LoggerInstance { return this.#logger; } [kGetParseContext](): Object { return this.#parseContext || {}; } [kGetUsageInstance](): UsageInstance { return this.#usage; } [kGetValidationInstance](): ValidationInstance { return this.#validation; } [kHasParseCallback](): boolean { return !!this.#parseFn; } [kIsGlobalContext](): boolean { return this.#isGlobalContext; } [kPostProcess]<T extends Arguments | Promise<Arguments>>( argv: Arguments | Promise<Arguments>, populateDoubleDash: boolean, calledFromCommand: boolean, runGlobalMiddleware: boolean ): any { if (calledFromCommand) return argv; if (isPromise(argv)) return argv; if (!populateDoubleDash) { argv = this[kCopyDoubleDash](argv); } const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; if (parsePositionalNumbers) { argv = this[kParsePositionalNumbers](argv as Arguments); } if (runGlobalMiddleware) { argv = applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), false ); } return argv; } // put yargs back into an initial state; this is used mainly for running // commands in a breadth first manner: [kReset](aliases: Aliases = {}): YargsInstance { this.#options = this.#options || ({} as Options); const tmpOptions = {} as Options; tmpOptions.local = this.#options.local || []; tmpOptions.configObjects = this.#options.configObjects || []; // if a key has been explicitly set as local, // we should reset it before passing options to command. const localLookup: Dictionary<boolean> = {}; tmpOptions.local.forEach(l => { localLookup[l] = true; (aliases[l] || []).forEach(a => { localLookup[a] = true; }); }); // add all groups not set to local to preserved groups Object.assign( this.#preservedGroups, Object.keys(this.#groups).reduce((acc, groupName) => { const keys = this.#groups[groupName].filter( key => !(key in localLookup) ); if (keys.length > 0) { acc[groupName] = keys; } return acc; }, {} as Dictionary<string[]>) ); // groups can now be reset this.#groups = {}; const arrayOptions: KeyOf<Options, string[]>[] = [ 'array', 'boolean', 'string', 'skipValidation', 'count', 'normalize', 'number', 'hiddenOptions', ]; const objectOptions: DictionaryKeyof<Options>[] = [ 'narg', 'key', 'alias', 'default', 'defaultDescription', 'config', 'choices', 'demandedOptions', 'demandedCommands', 'deprecatedOptions', ]; arrayOptions.forEach(k => { tmpOptions[k] = (this.#options[k] || []).filter( (k: string) => !localLookup[k] ); }); objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => { tmpOptions[k] = objFilter( this.#options[k], k => !localLookup[k as string] ); }); tmpOptions.envPrefix = this.#options.envPrefix; this.#options = tmpOptions; // if this is the first time being executed, create // instances of all our helpers -- otherwise just reset. this.#usage = this.#usage ? this.#usage.reset(localLookup) : Usage(this, this.#shim); this.#validation = this.#validation ? this.#validation.reset(localLookup) : Validation(this, this.#usage, this.#shim); this.#command = this.#command ? this.#command.reset() : Command( this.#usage, this.#validation, this.#globalMiddleware, this.#shim ); if (!this.#completion) this.#completion = Completion( this, this.#usage, this.#command, this.#shim ); this.#globalMiddleware.reset(); this.#completionCommand = null; this.#output = ''; this.#exitError = null; this.#hasOutput = false; this.parsed = false; return this; } [kRebase](base: string, dir: string): string { return this.#shim.path.relative(base, dir); } [kRunYargsParserAndExecuteCommands]( args: string | string[] | null, shortCircuit?: boolean | null, calledFromCommand?: boolean, commandIndex = 0, helpOnly = false ): Arguments | Promise<Arguments> { let skipValidation = !!calledFromCommand || helpOnly; args = args || this.#processArgs; this.#options.__ = this.#shim.y18n.__; this.#options.configuration = this[kGetParserConfiguration](); const populateDoubleDash = !!this.#options.configuration['populate--']; const config = Object.assign({}, this.#options.configuration, { 'populate--': true, }); const parsed = this.#shim.Parser.detailed( args, Object.assign({}, this.#options, { configuration: {'parse-positional-numbers': false, ...config}, }) ) as DetailedArguments; const argv: Arguments = Object.assign( parsed.argv, this.#parseContext ) as Arguments; let argvPromise: Arguments | Promise<Arguments> | undefined = undefined; const aliases = parsed.aliases; let helpOptSet = false; let versionOptSet = false; Object.keys(argv).forEach(key => { if (key === this.#helpOpt && argv[key]) { helpOptSet = true; } else if (key === this.#versionOpt && argv[key]) { versionOptSet = true; } }); argv.$0 = this.$0; this.parsed = parsed; // A single yargs instance may be used multiple times, e.g. // const y = yargs(); y.parse('foo --bar'); yargs.parse('bar --foo'). // When a prior parse has completed and a new parse is beginning, we // need to clear the cached help message from the previous parse: if (commandIndex === 0) { this.#usage.clearCachedHelpMessage(); } try { this[kGuessLocale](); // guess locale lazily, so that it can be turned off in chain. // while building up the argv object, there // are two passes through the parser. If completion // is being performed short-circuit on the first pass. if (shortCircuit) { return this[kPostProcess]( argv, populateDoubleDash, !!calledFromCommand, false // Don't run middleware when figuring out completion. ); } // if there's a handler associated with a // command defer processing to it. if (this.#helpOpt) { // consider any multi-char helpOpt alias as a valid help command // unless all helpOpt aliases are single-char // note that parsed.aliases is a normalized bidirectional map :) const helpCmds = [this.#helpOpt] .concat(aliases[this.#helpOpt] || []) .filter(k => k.length > 1); // check if help should trigger and strip it from _. if (helpCmds.includes('' + argv._[argv._.length - 1])) { argv._.pop(); helpOptSet = true; } } this.#isGlobalContext = false; const handlerKeys = this.#command.getCommands(); const requestCompletions = this.#completion!.completionKey in argv; const skipRecommendation = helpOptSet || requestCompletions || helpOnly; if (argv._.length) { if (handlerKeys.length) { let firstUnknownCommand; for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { cmd = String(argv._[i]); if (handlerKeys.includes(cmd) && cmd !== this.#completionCommand) { // commands are executed using a recursive algorithm that executes // the deepest command first; we keep track of the position in the // argv._ array that is currently being executed. const innerArgv = this.#command.runCommand( cmd, this, parsed, i + 1, // Don't run a handler, just figure out the help string: helpOnly, // Passed to builder so that expensive commands can be deferred: helpOptSet || versionOptSet || helpOnly ); return this[kPostProcess]( innerArgv, populateDoubleDash, !!calledFromCommand, false ); } else if ( !firstUnknownCommand && cmd !== this.#completionCommand ) { firstUnknownCommand = cmd; break; } } // recommend a command if recommendCommands() has // been enabled, and no commands were found to execute if ( !this.#command.hasDefaultCommand() && this.#recommendCommands && firstUnknownCommand && !skipRecommendation ) { this.#validation.recommendCommands( firstUnknownCommand, handlerKeys ); } } // generate a completion script for adding to ~/.bashrc. if ( this.#completionCommand && argv._.includes(this.#completionCommand) && !requestCompletions ) { if (this.#exitProcess) setBlocking(true); this.showCompletionScript(); this.exit(0); } } if (this.#command.hasDefaultCommand() && !skipRecommendation) { const innerArgv = this.#command.runCommand( null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly ); return this[kPostProcess]( innerArgv, populateDoubleDash, !!calledFromCommand, false ); } // we must run completions first, a user might // want to complete the --help or --version option. if (requestCompletions) { if (this.#exitProcess) setBlocking(true); // we allow for asynchronous completions, // e.g., loading in a list of commands from an API. args = ([] as string[]).concat(args); const completionArgs = args.slice( args.indexOf(`--${this.#completion!.completionKey}`) + 1 ); this.#completion!.getCompletion(completionArgs, (err, completions) => { if (err) throw new YError(err.message); (completions || []).forEach(completion => { this.#logger.log(completion); }); this.exit(0); }); return this[kPostProcess]( argv, !populateDoubleDash, !!calledFromCommand, false // Don't run middleware when figuring out completion. ); } // Handle 'help' and 'version' options // if we haven't already output help! if (!this.#hasOutput) { if (helpOptSet) { if (this.#exitProcess) setBlocking(true); skipValidation = true; this.showHelp('log'); this.exit(0); } else if (versionOptSet) { if (this.#exitProcess) setBlocking(true); skipValidation = true; this.#usage.showVersion('log'); this.exit(0); } } // Check if any of the options to skip validation were provided if (!skipValidation && this.#options.skipValidation.length > 0) { skipValidation = Object.keys(argv).some( key => this.#options.skipValidation.indexOf(key) >= 0 && argv[key] === true ); } // If the help or version options were used and exitProcess is false, // or if explicitly skipped, we won't run validations. if (!skipValidation) { if (parsed.error) throw new YError(parsed.error.message); // if we're executed via bash completion, don't // bother with validation. if (!requestCompletions) { const validation = this[kRunValidation](aliases, {}, parsed.error); if (!calledFromCommand) { argvPromise = applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), true ); } argvPromise = this[kValidateAsync](validation, argvPromise ?? argv); if (isPromise(argvPromise) && !calledFromCommand) { argvPromise = argvPromise.then(() => { return applyMiddleware( argv, this, this.#globalMiddleware.getMiddleware(), false ); }); } } } } catch (err) { if (err instanceof YError) this.#usage.fail(err.message, err); else throw err; } return this[kPostProcess]( argvPromise ?? argv, populateDoubleDash, !!calledFromCommand, true ); } [kRunValidation]( aliases: Dictionary<string[]>, positionalMap: Dictionary<string[]>, parseErrors: Error | null, isDefaultCommand?: boolean ): (argv: Arguments) => void { const demandedOptions = {...this.getDemandedOptions()}; return (argv: Arguments) => { if (parseErrors) throw new YError(parseErrors.message); this.#validation.nonOptionCount(argv); this.#validation.requiredArguments(argv, demandedOptions); let failedStrictCommands = false; if (this.#strictCommands) { failedStrictCommands = this.#validation.unknownCommands(argv); } if (this.#strict && !failedStrictCommands) { this.#validation.unknownArguments( argv, aliases, positionalMap, !!isDefaultCommand ); } else if (this.#strictOptions) { this.#validation.unknownArguments(argv, aliases, {}, false, false); } this.#validation.limitedChoices(argv); this.#validation.implications(argv); this.#validation.conflicting(argv); }; } [kSetHasOutput]() { this.#hasOutput = true; } [kTrackManuallySetKeys](keys: string | string[]) { if (typeof keys === 'string') { this.#options.key[keys] = true; } else { for (const k of keys) { this.#options.key[k] = true; } } } }
2,905
parserConfiguration(config: Configuration) { argsert('<object>', [config], arguments.length); this.#parserConfig = config; return this; }
interface Configuration extends Partial<ParserConfiguration> { /** Should a config object be deep-merged with the object config it extends? */ 'deep-merge-config'?: boolean; /** Should commands be sorted in help? */ 'sort-commands'?: boolean; }
2,906
parserConfiguration(config: Configuration) { argsert('<object>', [config], arguments.length); this.#parserConfig = config; return this; }
interface Configuration { /** Should variables prefixed with --no be treated as negations? Default is `true` */ 'boolean-negation': boolean; /** Should hyphenated arguments be expanded into camel-case aliases? Default is `true` */ 'camel-case-expansion': boolean; /** Should arrays be combined when provided by both command line arguments and a configuration file? Default is `false` */ 'combine-arrays': boolean; /** Should keys that contain `.` be treated as objects? Default is `true` */ 'dot-notation': boolean; /** Should arguments be coerced into an array when duplicated? Default is `true` */ 'duplicate-arguments-array': boolean; /** Should array arguments be coerced into a single array when duplicated? Default is `true` */ 'flatten-duplicate-arrays': boolean; /** Should arrays consume more than one positional argument following their flag? Default is `true` */ 'greedy-arrays': boolean; /** Should parsing stop at the first text argument? This is similar to how e.g. ssh parses its command line. Default is `false` */ 'halt-at-non-option': boolean; /** Should nargs consume dash options as well as positional arguments? Default is `false` */ 'nargs-eats-options': boolean; /** The prefix to use for negated boolean variables. Default is `'no-'` */ 'negation-prefix': string; /** Should positional values that look like numbers be parsed? Default is `true` */ 'parse-positional-numbers': boolean; /** Should keys that look like numbers be treated as such? Default is `true` */ 'parse-numbers': boolean; /** Should unparsed flags be stored in -- or _? Default is `false` */ 'populate--': boolean; /** Should a placeholder be added for keys not set via the corresponding CLI argument? Default is `false` */ 'set-placeholder-key': boolean; /** Should a group of short-options be treated as boolean flags? Default is `true` */ 'short-option-groups': boolean; /** Should aliases be removed before returning results? Default is `false` */ 'strip-aliased': boolean; /** Should dashed keys be removed before returning results? This option has no effect if camel-case-expansion is disabled. Default is `false` */ 'strip-dashed': boolean; /** Should unknown options be treated like regular arguments? An unknown option is one that is not configured in opts. Default is `false` */ 'unknown-options-as-args': boolean; }
2,907
usageConfiguration(config: UsageConfiguration) { argsert('<object>', [config], arguments.length); this.#usageConfig = config; return this; }
interface UsageConfiguration { /** Should types be hidden when usage is displayed */ 'hide-types'?: boolean; }
2,908
[kCopyDoubleDash](argv: Arguments): any { if (!argv._ || !argv['--']) return argv; // eslint-disable-next-line prefer-spread argv._.push.apply(argv._, argv['--']); // We catch an error here, in case someone has called Object.seal() // on the parsed object, see: https://github.com/babel/babel/pull/10733 try { delete argv['--']; // eslint-disable-next-line no-empty } catch (_err) {} return argv; }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,909
[kCopyDoubleDash](argv: Arguments): any { if (!argv._ || !argv['--']) return argv; // eslint-disable-next-line prefer-spread argv._.push.apply(argv._, argv['--']); // We catch an error here, in case someone has called Object.seal() // on the parsed object, see: https://github.com/babel/babel/pull/10733 try { delete argv['--']; // eslint-disable-next-line no-empty } catch (_err) {} return argv; }
interface Arguments { /** The script name or node command */ $0: string; /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,910
[kCopyDoubleDash](argv: Arguments): any { if (!argv._ || !argv['--']) return argv; // eslint-disable-next-line prefer-spread argv._.push.apply(argv._, argv['--']); // We catch an error here, in case someone has called Object.seal() // on the parsed object, see: https://github.com/babel/babel/pull/10733 try { delete argv['--']; // eslint-disable-next-line no-empty } catch (_err) {} return argv; }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,911
[kParsePositionalNumbers](argv: Arguments): any { const args: (string | number)[] = argv['--'] ? argv['--'] : argv._; for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { if ( this.#shim.Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`))) ) { args[i] = Number(arg); } } return argv; }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,912
[kParsePositionalNumbers](argv: Arguments): any { const args: (string | number)[] = argv['--'] ? argv['--'] : argv._; for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { if ( this.#shim.Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`))) ) { args[i] = Number(arg); } } return argv; }
interface Arguments { /** The script name or node command */ $0: string; /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,913
[kParsePositionalNumbers](argv: Arguments): any { const args: (string | number)[] = argv['--'] ? argv['--'] : argv._; for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { if ( this.#shim.Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`))) ) { args[i] = Number(arg); } } return argv; }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,914
[kReset](aliases: Aliases = {}): YargsInstance { this.#options = this.#options || ({} as Options); const tmpOptions = {} as Options; tmpOptions.local = this.#options.local || []; tmpOptions.configObjects = this.#options.configObjects || []; // if a key has been explicitly set as local, // we should reset it before passing options to command. const localLookup: Dictionary<boolean> = {}; tmpOptions.local.forEach(l => { localLookup[l] = true; (aliases[l] || []).forEach(a => { localLookup[a] = true; }); }); // add all groups not set to local to preserved groups Object.assign( this.#preservedGroups, Object.keys(this.#groups).reduce((acc, groupName) => { const keys = this.#groups[groupName].filter( key => !(key in localLookup) ); if (keys.length > 0) { acc[groupName] = keys; } return acc; }, {} as Dictionary<string[]>) ); // groups can now be reset this.#groups = {}; const arrayOptions: KeyOf<Options, string[]>[] = [ 'array', 'boolean', 'string', 'skipValidation', 'count', 'normalize', 'number', 'hiddenOptions', ]; const objectOptions: DictionaryKeyof<Options>[] = [ 'narg', 'key', 'alias', 'default', 'defaultDescription', 'config', 'choices', 'demandedOptions', 'demandedCommands', 'deprecatedOptions', ]; arrayOptions.forEach(k => { tmpOptions[k] = (this.#options[k] || []).filter( (k: string) => !localLookup[k] ); }); objectOptions.forEach(<K extends DictionaryKeyof<Options>>(k: K) => { tmpOptions[k] = objFilter( this.#options[k], k => !localLookup[k as string] ); }); tmpOptions.envPrefix = this.#options.envPrefix; this.#options = tmpOptions; // if this is the first time being executed, create // instances of all our helpers -- otherwise just reset. this.#usage = this.#usage ? this.#usage.reset(localLookup) : Usage(this, this.#shim); this.#validation = this.#validation ? this.#validation.reset(localLookup) : Validation(this, this.#usage, this.#shim); this.#command = this.#command ? this.#command.reset() : Command( this.#usage, this.#validation, this.#globalMiddleware, this.#shim ); if (!this.#completion) this.#completion = Completion( this, this.#usage, this.#command, this.#shim ); this.#globalMiddleware.reset(); this.#completionCommand = null; this.#output = ''; this.#exitError = null; this.#hasOutput = false; this.parsed = false; return this; }
interface Aliases { [key: string]: Array<string>; }
2,915
(argv: Arguments) => { if (parseErrors) throw new YError(parseErrors.message); this.#validation.nonOptionCount(argv); this.#validation.requiredArguments(argv, demandedOptions); let failedStrictCommands = false; if (this.#strictCommands) { failedStrictCommands = this.#validation.unknownCommands(argv); } if (this.#strict && !failedStrictCommands) { this.#validation.unknownArguments( argv, aliases, positionalMap, !!isDefaultCommand ); } else if (this.#strictOptions) { this.#validation.unknownArguments(argv, aliases, {}, false, false); } this.#validation.limitedChoices(argv); this.#validation.implications(argv); this.#validation.conflicting(argv); }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,916
(argv: Arguments) => { if (parseErrors) throw new YError(parseErrors.message); this.#validation.nonOptionCount(argv); this.#validation.requiredArguments(argv, demandedOptions); let failedStrictCommands = false; if (this.#strictCommands) { failedStrictCommands = this.#validation.unknownCommands(argv); } if (this.#strict && !failedStrictCommands) { this.#validation.unknownArguments( argv, aliases, positionalMap, !!isDefaultCommand ); } else if (this.#strictOptions) { this.#validation.unknownArguments(argv, aliases, {}, false, false); } this.#validation.limitedChoices(argv); this.#validation.implications(argv); this.#validation.conflicting(argv); }
interface Arguments { /** The script name or node command */ $0: string; /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,917
(argv: Arguments) => { if (parseErrors) throw new YError(parseErrors.message); this.#validation.nonOptionCount(argv); this.#validation.requiredArguments(argv, demandedOptions); let failedStrictCommands = false; if (this.#strictCommands) { failedStrictCommands = this.#validation.unknownCommands(argv); } if (this.#strict && !failedStrictCommands) { this.#validation.unknownArguments( argv, aliases, positionalMap, !!isDefaultCommand ); } else if (this.#strictOptions) { this.#validation.unknownArguments(argv, aliases, {}, false, false); } this.#validation.limitedChoices(argv); this.#validation.implications(argv); this.#validation.conflicting(argv); }
interface Arguments { /** Non-option arguments */ _: ArgsOutput; /** Arguments after the end-of-options flag `--` */ '--'?: ArgsOutput; /** All remaining options */ [argName: string]: any; }
2,918
(args: ArgsInput, opts?: Partial<Options>): Arguments
type ArgsInput = string | any[];
2,919
detailed(args: ArgsInput, opts?: Partial<Options>): DetailedArguments
type ArgsInput = string | any[];
2,920
function applyExtends( config: Dictionary, cwd: string, mergeExtends: boolean, _shim: PlatformShim ): Dictionary { shim = _shim; let defaultConfig = {}; if (Object.prototype.hasOwnProperty.call(config, 'extends')) { if (typeof config.extends !== 'string') return defaultConfig; const isPath = /\.json|\..*rc$/.test(config.extends); let pathToDefault: string | null = null; if (!isPath) { try { pathToDefault = require.resolve(config.extends); } catch (_err) { // maybe the module uses key for some other reason, // err on side of caution. return config; } } else { pathToDefault = getPathToDefaultConfig(cwd, config.extends); } checkForCircularExtends(pathToDefault); previouslyVisitedConfigs.push(pathToDefault); defaultConfig = isPath ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) : require(config.extends); delete config.extends; defaultConfig = applyExtends( defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim ); } previouslyVisitedConfigs = []; return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config); }
type Dictionary<T = any> = {[key: string]: T};
2,921
function applyExtends( config: Dictionary, cwd: string, mergeExtends: boolean, _shim: PlatformShim ): Dictionary { shim = _shim; let defaultConfig = {}; if (Object.prototype.hasOwnProperty.call(config, 'extends')) { if (typeof config.extends !== 'string') return defaultConfig; const isPath = /\.json|\..*rc$/.test(config.extends); let pathToDefault: string | null = null; if (!isPath) { try { pathToDefault = require.resolve(config.extends); } catch (_err) { // maybe the module uses key for some other reason, // err on side of caution. return config; } } else { pathToDefault = getPathToDefaultConfig(cwd, config.extends); } checkForCircularExtends(pathToDefault); previouslyVisitedConfigs.push(pathToDefault); defaultConfig = isPath ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) : require(config.extends); delete config.extends; defaultConfig = applyExtends( defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim ); } previouslyVisitedConfigs = []; return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config); }
interface PlatformShim { cwd: Function; format: Function; normalize: Function; require: Function; resolve: Function; env: Function; }
2,922
function applyExtends( config: Dictionary, cwd: string, mergeExtends: boolean, _shim: PlatformShim ): Dictionary { shim = _shim; let defaultConfig = {}; if (Object.prototype.hasOwnProperty.call(config, 'extends')) { if (typeof config.extends !== 'string') return defaultConfig; const isPath = /\.json|\..*rc$/.test(config.extends); let pathToDefault: string | null = null; if (!isPath) { try { pathToDefault = require.resolve(config.extends); } catch (_err) { // maybe the module uses key for some other reason, // err on side of caution. return config; } } else { pathToDefault = getPathToDefaultConfig(cwd, config.extends); } checkForCircularExtends(pathToDefault); previouslyVisitedConfigs.push(pathToDefault); defaultConfig = isPath ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) : require(config.extends); delete config.extends; defaultConfig = applyExtends( defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim ); } previouslyVisitedConfigs = []; return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config); }
interface PlatformShim { assert: { notStrictEqual: ( expected: any, observed: any, message?: string | Error ) => void; strictEqual: ( expected: any, observed: any, message?: string | Error ) => void; }; findUp: ( startDir: string, fn: (dir: string[], names: string[]) => string | undefined ) => string; getCallerFile: () => string; getEnv: (key: string) => string | undefined; getProcessArgvBin: () => string; inspect: (obj: object) => string; mainFilename: string; requireDirectory: Function; stringWidth: (str: string) => number; cliui: Function; Parser: Parser; path: { basename: (p1: string, p2?: string) => string; extname: (path: string) => string; dirname: (path: string) => string; relative: (p1: string, p2: string) => string; resolve: (p1: string, p2: string) => string; }; process: { argv: () => string[]; cwd: () => string; emitWarning: (warning: string | Error, type?: string) => void; execPath: () => string; exit: (code: number) => void; nextTick: (cb: Function) => void; stdColumns: number | null; }; readFileSync: (path: string, encoding: string) => string; require: RequireType; y18n: Y18N; }
2,923
function mergeDeep(config1: Dictionary, config2: Dictionary) { const target: Dictionary = {}; function isObject(obj: Dictionary | any): obj is Dictionary { return obj && typeof obj === 'object' && !Array.isArray(obj); } Object.assign(target, config1); for (const key of Object.keys(config2)) { if (isObject(config2[key]) && isObject(target[key])) { target[key] = mergeDeep(config1[key], config2[key]); } else { target[key] = config2[key]; } } return target; }
type Dictionary<T = any> = {[key: string]: T};
2,924
function renderNode(node: AnyNode, options: DomSerializerOptions): string { switch (node.type) { case ElementType.Root: return render(node.children, options); // @ts-expect-error We don't use `Doctype` yet case ElementType.Doctype: case ElementType.Directive: return renderDirective(node); case ElementType.Comment: return renderComment(node); case ElementType.CDATA: return renderCdata(node); case ElementType.Script: case ElementType.Style: case ElementType.Tag: return renderTag(node, options); case ElementType.Text: return renderText(node, options); } }
interface DomSerializerOptions { /** * Print an empty attribute's value. * * @default xmlMode * @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code> * @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code> */ emptyAttrs?: boolean; /** * Print self-closing tags for tags without contents. If `xmlMode` is set, this will apply to all tags. * Otherwise, only tags that are defined as self-closing in the HTML specification will be printed as such. * * @default xmlMode * @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br&gt;&lt;/br&gt;</code> * @example With <code>xmlMode: true</code> and <code>selfClosingTags: true</code>: <code>&lt;foo/&gt;&lt;br/&gt;</code> * @example With <code>xmlMode: false</code> and <code>selfClosingTags: true</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br /&gt;</code> */ selfClosingTags?: boolean; /** * Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options. * * If the value is `"foreign"`, it will try to correct mixed-case attribute names. * * @default false */ xmlMode?: boolean | "foreign"; /** * Encode characters that are either reserved in HTML or XML. * * If `xmlMode` is `true` or the value not `'utf8'`, characters outside of the utf8 range will be encoded as well. * * @default `decodeEntities` */ encodeEntities?: boolean | "utf8"; /** * Option inherited from parsing; will be used as the default value for `encodeEntities`. * * @default true */ decodeEntities?: boolean; }
2,925
function renderTag(elem: Element, opts: DomSerializerOptions) { // Handle SVG / MathML in HTML if (opts.xmlMode === "foreign") { /* Fix up mixed-case element names */ elem.name = elementNames.get(elem.name) ?? elem.name; /* Exit foreign mode at integration points */ if ( elem.parent && foreignModeIntegrationPoints.has((elem.parent as Element).name) ) { opts = { ...opts, xmlMode: false }; } } if (!opts.xmlMode && foreignElements.has(elem.name)) { opts = { ...opts, xmlMode: "foreign" }; } let tag = `<${elem.name}`; const attribs = formatAttributes(elem.attribs, opts); if (attribs) { tag += ` ${attribs}`; } if ( elem.children.length === 0 && (opts.xmlMode ? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags opts.selfClosingTags !== false : // User explicitly asked for self-closing tags, even in HTML mode opts.selfClosingTags && singleTag.has(elem.name)) ) { if (!opts.xmlMode) tag += " "; tag += "/>"; } else { tag += ">"; if (elem.children.length > 0) { tag += render(elem.children, opts); } if (opts.xmlMode || !singleTag.has(elem.name)) { tag += `</${elem.name}>`; } } return tag; }
interface DomSerializerOptions { /** * Print an empty attribute's value. * * @default xmlMode * @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code> * @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code> */ emptyAttrs?: boolean; /** * Print self-closing tags for tags without contents. If `xmlMode` is set, this will apply to all tags. * Otherwise, only tags that are defined as self-closing in the HTML specification will be printed as such. * * @default xmlMode * @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br&gt;&lt;/br&gt;</code> * @example With <code>xmlMode: true</code> and <code>selfClosingTags: true</code>: <code>&lt;foo/&gt;&lt;br/&gt;</code> * @example With <code>xmlMode: false</code> and <code>selfClosingTags: true</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br /&gt;</code> */ selfClosingTags?: boolean; /** * Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options. * * If the value is `"foreign"`, it will try to correct mixed-case attribute names. * * @default false */ xmlMode?: boolean | "foreign"; /** * Encode characters that are either reserved in HTML or XML. * * If `xmlMode` is `true` or the value not `'utf8'`, characters outside of the utf8 range will be encoded as well. * * @default `decodeEntities` */ encodeEntities?: boolean | "utf8"; /** * Option inherited from parsing; will be used as the default value for `encodeEntities`. * * @default true */ decodeEntities?: boolean; }
2,926
function renderText(elem: Text, opts: DomSerializerOptions) { let data = elem.data || ""; // If entities weren't decoded, no need to encode them back if ( (opts.encodeEntities ?? opts.decodeEntities) !== false && !( !opts.xmlMode && elem.parent && unencodedElements.has((elem.parent as Element).name) ) ) { data = opts.xmlMode || opts.encodeEntities !== "utf8" ? encodeXML(data) : escapeText(data); } return data; }
interface DomSerializerOptions { /** * Print an empty attribute's value. * * @default xmlMode * @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code> * @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code> */ emptyAttrs?: boolean; /** * Print self-closing tags for tags without contents. If `xmlMode` is set, this will apply to all tags. * Otherwise, only tags that are defined as self-closing in the HTML specification will be printed as such. * * @default xmlMode * @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br&gt;&lt;/br&gt;</code> * @example With <code>xmlMode: true</code> and <code>selfClosingTags: true</code>: <code>&lt;foo/&gt;&lt;br/&gt;</code> * @example With <code>xmlMode: false</code> and <code>selfClosingTags: true</code>: <code>&lt;foo&gt;&lt;/foo&gt;&lt;br /&gt;</code> */ selfClosingTags?: boolean; /** * Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options. * * If the value is `"foreign"`, it will try to correct mixed-case attribute names. * * @default false */ xmlMode?: boolean | "foreign"; /** * Encode characters that are either reserved in HTML or XML. * * If `xmlMode` is `true` or the value not `'utf8'`, characters outside of the utf8 range will be encoded as well. * * @default `decodeEntities` */ encodeEntities?: boolean | "utf8"; /** * Option inherited from parsing; will be used as the default value for `encodeEntities`. * * @default true */ decodeEntities?: boolean; }
2,927
function html( preset: CheerioOptions, str: string, options: CheerioOptions = {} ) { const opts = { ...defaultOpts, ...preset, ...options }; const dom = parse(str, opts, true) as Document; return render(dom, opts); }
interface CheerioOptions extends DomSerializerOptions { _useHtmlParser2?: boolean; }
2,928
(ctx: Context, rec: Recogniser, confidence: number): Match => ({ confidence, name: rec.name(ctx), lang: rec.language ? rec.language() : undefined, })
interface Recogniser { match(input: Context): Match | null; name(input?: Context): string; language?(): string | undefined; }
2,929
(ctx: Context, rec: Recogniser, confidence: number): Match => ({ confidence, name: rec.name(ctx), lang: rec.language ? rec.language() : undefined, })
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,930
match(input: Context): Match | null
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,931
name(input?: Context): string
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,932
nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,933
match(det: Context): Match | null { let doubleByteCharCount = 0, commonCharCount = 0, badCharCount = 0, totalCharCount = 0, confidence = 0; const iter = new IteratedChar(); detectBlock: { for (iter.reset(); this.nextChar(iter, det); ) { totalCharCount++; if (iter.error) { badCharCount++; } else { const cv = iter.charValue & 0xffffffff; if (cv > 0xff) { doubleByteCharCount++; if (this.commonChars != null) { // NOTE: This assumes that there are no 4-byte common chars. if (binarySearch(this.commonChars, cv) >= 0) { commonCharCount++; } } } } if (badCharCount >= 2 && badCharCount * 5 >= doubleByteCharCount) { // console.log('its here!') // Bail out early if the byte data is not matching the encoding scheme. break detectBlock; } } if (doubleByteCharCount <= 10 && badCharCount == 0) { // Not many multi-byte chars. if (doubleByteCharCount == 0 && totalCharCount < 10) { // There weren't any multibyte sequences, and there was a low density of non-ASCII single bytes. // We don't have enough data to have any confidence. // Statistical analysis of single byte non-ASCII characters would probably help here. confidence = 0; } else { // ASCII or ISO file? It's probably not our encoding, // but is not incompatible with our encoding, so don't give it a zero. confidence = 10; } break detectBlock; } // // No match if there are too many characters that don't fit the encoding scheme. // (should we have zero tolerance for these?) // if (doubleByteCharCount < 20 * badCharCount) { confidence = 0; break detectBlock; } if (this.commonChars == null) { // We have no statistics on frequently occurring characters. // Assess confidence purely on having a reasonable number of // multi-byte characters (the more the better confidence = 30 + doubleByteCharCount - 20 * badCharCount; if (confidence > 100) { confidence = 100; } } else { // Frequency of occurrence statistics exist. const maxVal = Math.log(doubleByteCharCount / 4); const scaleFactor = 90.0 / maxVal; confidence = Math.floor( Math.log(commonCharCount + 1) * scaleFactor + 10 ); confidence = Math.min(confidence, 100); } } // end of detectBlock: return confidence == 0 ? null : match(det, this, confidence); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,934
nextChar(_iter: IteratedChar, _det: Context): boolean { return true; }
class IteratedChar { charValue: number; // 1-4 bytes from the raw input data index: number; nextIndex: number; error: boolean; done: boolean; constructor() { this.charValue = 0; // 1-4 bytes from the raw input data this.index = 0; this.nextIndex = 0; this.error = false; this.done = false; } reset() { this.charValue = 0; this.index = -1; this.nextIndex = 0; this.error = false; this.done = false; } nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; } }
2,935
nextChar(_iter: IteratedChar, _det: Context): boolean { return true; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,936
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; const firstByte = (iter.charValue = iter.nextByte(det)); if (firstByte < 0) return false; if (firstByte <= 0x7f || (firstByte > 0xa0 && firstByte <= 0xdf)) return true; const secondByte = iter.nextByte(det); if (secondByte < 0) return false; iter.charValue = (firstByte << 8) | secondByte; if ( !( (secondByte >= 0x40 && secondByte <= 0x7f) || (secondByte >= 0x80 && secondByte <= 0xff) ) ) { // Illegal second byte value. iter.error = true; } return true; }
class IteratedChar { charValue: number; // 1-4 bytes from the raw input data index: number; nextIndex: number; error: boolean; done: boolean; constructor() { this.charValue = 0; // 1-4 bytes from the raw input data this.index = 0; this.nextIndex = 0; this.error = false; this.done = false; } reset() { this.charValue = 0; this.index = -1; this.nextIndex = 0; this.error = false; this.done = false; } nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; } }
2,937
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; const firstByte = (iter.charValue = iter.nextByte(det)); if (firstByte < 0) return false; if (firstByte <= 0x7f || (firstByte > 0xa0 && firstByte <= 0xdf)) return true; const secondByte = iter.nextByte(det); if (secondByte < 0) return false; iter.charValue = (firstByte << 8) | secondByte; if ( !( (secondByte >= 0x40 && secondByte <= 0x7f) || (secondByte >= 0x80 && secondByte <= 0xff) ) ) { // Illegal second byte value. iter.error = true; } return true; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,938
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; const firstByte = (iter.charValue = iter.nextByte(det)); if (firstByte < 0) return false; // single byte character. if (firstByte <= 0x7f || firstByte == 0xff) return true; const secondByte = iter.nextByte(det); if (secondByte < 0) return false; iter.charValue = (iter.charValue << 8) | secondByte; if (secondByte < 0x40 || secondByte == 0x7f || secondByte == 0xff) iter.error = true; return true; }
class IteratedChar { charValue: number; // 1-4 bytes from the raw input data index: number; nextIndex: number; error: boolean; done: boolean; constructor() { this.charValue = 0; // 1-4 bytes from the raw input data this.index = 0; this.nextIndex = 0; this.error = false; this.done = false; } reset() { this.charValue = 0; this.index = -1; this.nextIndex = 0; this.error = false; this.done = false; } nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; } }
2,939
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; const firstByte = (iter.charValue = iter.nextByte(det)); if (firstByte < 0) return false; // single byte character. if (firstByte <= 0x7f || firstByte == 0xff) return true; const secondByte = iter.nextByte(det); if (secondByte < 0) return false; iter.charValue = (iter.charValue << 8) | secondByte; if (secondByte < 0x40 || secondByte == 0x7f || secondByte == 0xff) iter.error = true; return true; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,940
function eucNextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; let firstByte = 0; let secondByte = 0; let thirdByte = 0; //int fourthByte = 0; buildChar: { firstByte = iter.charValue = iter.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data iter.done = true; break buildChar; } if (firstByte <= 0x8d) { // single byte char break buildChar; } secondByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | secondByte; if (firstByte >= 0xa1 && firstByte <= 0xfe) { // Two byte Char if (secondByte < 0xa1) { iter.error = true; } break buildChar; } if (firstByte == 0x8e) { // Code Set 2. // In EUC-JP, total char size is 2 bytes, only one byte of actual char value. // In EUC-TW, total char size is 4 bytes, three bytes contribute to char value. // We don't know which we've got. // Treat it like EUC-JP. If the data really was EUC-TW, the following two // bytes will look like a well formed 2 byte char. if (secondByte < 0xa1) { iter.error = true; } break buildChar; } if (firstByte == 0x8f) { // Code set 3. // Three byte total char size, two bytes of actual char value. thirdByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | thirdByte; if (thirdByte < 0xa1) { iter.error = true; } } } return iter.done == false; }
class IteratedChar { charValue: number; // 1-4 bytes from the raw input data index: number; nextIndex: number; error: boolean; done: boolean; constructor() { this.charValue = 0; // 1-4 bytes from the raw input data this.index = 0; this.nextIndex = 0; this.error = false; this.done = false; } reset() { this.charValue = 0; this.index = -1; this.nextIndex = 0; this.error = false; this.done = false; } nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; } }
2,941
function eucNextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; let firstByte = 0; let secondByte = 0; let thirdByte = 0; //int fourthByte = 0; buildChar: { firstByte = iter.charValue = iter.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data iter.done = true; break buildChar; } if (firstByte <= 0x8d) { // single byte char break buildChar; } secondByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | secondByte; if (firstByte >= 0xa1 && firstByte <= 0xfe) { // Two byte Char if (secondByte < 0xa1) { iter.error = true; } break buildChar; } if (firstByte == 0x8e) { // Code Set 2. // In EUC-JP, total char size is 2 bytes, only one byte of actual char value. // In EUC-TW, total char size is 4 bytes, three bytes contribute to char value. // We don't know which we've got. // Treat it like EUC-JP. If the data really was EUC-TW, the following two // bytes will look like a well formed 2 byte char. if (secondByte < 0xa1) { iter.error = true; } break buildChar; } if (firstByte == 0x8f) { // Code set 3. // Three byte total char size, two bytes of actual char value. thirdByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | thirdByte; if (thirdByte < 0xa1) { iter.error = true; } } } return iter.done == false; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,942
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; let firstByte = 0; let secondByte = 0; let thirdByte = 0; let fourthByte = 0; buildChar: { firstByte = iter.charValue = iter.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data iter.done = true; break buildChar; } if (firstByte <= 0x80) { // single byte char break buildChar; } secondByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | secondByte; if (firstByte >= 0x81 && firstByte <= 0xfe) { // Two byte Char if ( (secondByte >= 0x40 && secondByte <= 0x7e) || (secondByte >= 80 && secondByte <= 0xfe) ) { break buildChar; } // Four byte char if (secondByte >= 0x30 && secondByte <= 0x39) { thirdByte = iter.nextByte(det); if (thirdByte >= 0x81 && thirdByte <= 0xfe) { fourthByte = iter.nextByte(det); if (fourthByte >= 0x30 && fourthByte <= 0x39) { iter.charValue = (iter.charValue << 16) | (thirdByte << 8) | fourthByte; break buildChar; } } } iter.error = true; break buildChar; } } return iter.done == false; }
class IteratedChar { charValue: number; // 1-4 bytes from the raw input data index: number; nextIndex: number; error: boolean; done: boolean; constructor() { this.charValue = 0; // 1-4 bytes from the raw input data this.index = 0; this.nextIndex = 0; this.error = false; this.done = false; } reset() { this.charValue = 0; this.index = -1; this.nextIndex = 0; this.error = false; this.done = false; } nextByte(det: Context) { if (this.nextIndex >= det.rawLen) { this.done = true; return -1; } const byteValue = det.rawInput[this.nextIndex++] & 0x00ff; return byteValue; } }
2,943
nextChar(iter: IteratedChar, det: Context) { iter.index = iter.nextIndex; iter.error = false; let firstByte = 0; let secondByte = 0; let thirdByte = 0; let fourthByte = 0; buildChar: { firstByte = iter.charValue = iter.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data iter.done = true; break buildChar; } if (firstByte <= 0x80) { // single byte char break buildChar; } secondByte = iter.nextByte(det); iter.charValue = (iter.charValue << 8) | secondByte; if (firstByte >= 0x81 && firstByte <= 0xfe) { // Two byte Char if ( (secondByte >= 0x40 && secondByte <= 0x7e) || (secondByte >= 80 && secondByte <= 0xfe) ) { break buildChar; } // Four byte char if (secondByte >= 0x30 && secondByte <= 0x39) { thirdByte = iter.nextByte(det); if (thirdByte >= 0x81 && thirdByte <= 0xfe) { fourthByte = iter.nextByte(det); if (fourthByte >= 0x30 && fourthByte <= 0x39) { iter.charValue = (iter.charValue << 16) | (thirdByte << 8) | fourthByte; break buildChar; } } } iter.error = true; break buildChar; } } return iter.done == false; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,944
match(det: Context): Match | null { const input = det.rawInput; if ( input.length >= 2 && (input[0] & 0xff) == 0xfe && (input[1] & 0xff) == 0xff ) { return match(det, this, 100); // confidence = 100 } // TODO: Do some statistics to check for unsigned UTF-16BE return null; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,945
match(det: Context): Match | null { const input = det.rawInput; if ( input.length >= 2 && (input[0] & 0xff) == 0xff && (input[1] & 0xff) == 0xfe ) { // LE BOM is present. if (input.length >= 4 && input[2] == 0x00 && input[3] == 0x00) { // It is probably UTF-32 LE, not UTF-16 return null; } return match(det, this, 100); // confidence = 100 } // TODO: Do some statistics to check for unsigned UTF-16LE return null; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,946
match(det: Context): Match | null { let numValid = 0, numInvalid = 0, hasBOM = false, confidence = 0; const limit = (det.rawLen / 4) * 4; const input = det.rawInput; if (limit == 0) { return null; } if (this.getChar(input, 0) == 0x0000feff) { hasBOM = true; } for (let i = 0; i < limit; i += 4) { const ch = this.getChar(input, i); if (ch < 0 || ch >= 0x10ffff || (ch >= 0xd800 && ch <= 0xdfff)) { numInvalid += 1; } else { numValid += 1; } } // Cook up some sort of confidence score, based on presence of a BOM // and the existence of valid and/or invalid multi-byte sequences. if (hasBOM && numInvalid == 0) { confidence = 100; } else if (hasBOM && numValid > numInvalid * 10) { confidence = 80; } else if (numValid > 3 && numInvalid == 0) { confidence = 100; } else if (numValid > 0 && numInvalid == 0) { confidence = 80; } else if (numValid > numInvalid * 10) { // Probably corrupt UTF-32BE data. Valid sequences aren't likely by chance. confidence = 25; } // return confidence == 0 ? null : new CharsetMatch(det, this, confidence); return confidence == 0 ? null : match(det, this, confidence); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,947
match(det: Context): Match | null { let hasBOM = false, numValid = 0, numInvalid = 0, trailBytes = 0, confidence; const input = det.rawInput; if ( det.rawLen >= 3 && (input[0] & 0xff) == 0xef && (input[1] & 0xff) == 0xbb && (input[2] & 0xff) == 0xbf ) { hasBOM = true; } // Scan for multi-byte sequences for (let i = 0; i < det.rawLen; i++) { const b = input[i]; if ((b & 0x80) == 0) continue; // ASCII // Hi bit on char found. Figure out how long the sequence should be if ((b & 0x0e0) == 0x0c0) { trailBytes = 1; } else if ((b & 0x0f0) == 0x0e0) { trailBytes = 2; } else if ((b & 0x0f8) == 0xf0) { trailBytes = 3; } else { numInvalid++; if (numInvalid > 5) break; trailBytes = 0; } // Verify that we've got the right number of trail bytes in the sequence for (;;) { i++; if (i >= det.rawLen) break; if ((input[i] & 0xc0) != 0x080) { numInvalid++; break; } if (--trailBytes == 0) { numValid++; break; } } } // Cook up some sort of confidence score, based on presense of a BOM // and the existence of valid and/or invalid multi-byte sequences. confidence = 0; if (hasBOM && numInvalid == 0) confidence = 100; else if (hasBOM && numValid > numInvalid * 10) confidence = 80; else if (numValid > 3 && numInvalid == 0) confidence = 100; else if (numValid > 0 && numInvalid == 0) confidence = 80; else if (numValid == 0 && numInvalid == 0) // Plain ASCII. confidence = 10; else if (numValid > numInvalid * 10) // Probably corrupt utf-8 data. Valid sequences aren't likely by chance. confidence = 25; else return null; return match(det, this, confidence); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,948
match(det: Context): Match | null { /** * Matching function shared among the 2022 detectors JP, CN and KR * Counts up the number of legal an unrecognized escape sequences in * the sample of text, and computes a score based on the total number & * the proportion that fit the encoding. * * * @param text the byte buffer containing text to analyse * @param textLen the size of the text in the byte. * @param escapeSequences the byte escape sequences to test for. * @return match quality, in the range of 0-100. */ let i, j; let escN; let hits = 0; let misses = 0; let shifts = 0; let confidence; // TODO: refactor me const text = det.inputBytes; const textLen = det.inputLen; scanInput: for (i = 0; i < textLen; i++) { if (text[i] == 0x1b) { checkEscapes: for ( escN = 0; escN < this.escapeSequences.length; escN++ ) { const seq = this.escapeSequences[escN]; if (textLen - i < seq.length) continue checkEscapes; for (j = 1; j < seq.length; j++) if (seq[j] != text[i + j]) continue checkEscapes; hits++; i += seq.length - 1; continue scanInput; } misses++; } // Shift in/out if (text[i] == 0x0e || text[i] == 0x0f) shifts++; } if (hits == 0) return null; // // Initial quality is based on relative proportion of recognized vs. // unrecognized escape sequences. // All good: quality = 100; // half or less good: quality = 0; // linear in between. confidence = (100 * hits - 100 * misses) / (hits + misses); // Back off quality if there were too few escape sequences seen. // Include shifts in this computation, so that KR does not get penalized // for having only a single Escape sequence, but many shifts. if (hits + shifts < 5) confidence -= (5 - (hits + shifts)) * 10; return confidence <= 0 ? null : match(det, this, confidence); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,949
nextByte(det: Context) { if (this.byteIndex >= det.inputLen) return -1; return det.inputBytes[this.byteIndex++] & 0xff; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,950
parse(det: Context, spaceCh: number) { let b, ignoreSpace = false; this.spaceChar = spaceCh; while ((b = this.nextByte(det)) >= 0) { const mb = this.byteMap[b]; // TODO: 0x20 might not be a space in all character sets... if (mb != 0) { if (!(mb == this.spaceChar && ignoreSpace)) { this.addByte(mb); } ignoreSpace = mb == this.spaceChar; } } // TODO: Is this OK? The buffer could have ended in the middle of a word... this.addByte(this.spaceChar); const rawPercent = this.hitCount / this.ngramCount; // TODO - This is a bit of a hack to take care of a case // were we were getting a confidence of 135... if (rawPercent > 0.33) return 98; return Math.floor(rawPercent * 300.0); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,951
name(_input: Context): string { return 'sbcs'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,952
match(det: Context): Match | null { // This feels a bit dirty. Simpler alternative would be // splitting classes ISO_8859_1 etc into language-specific ones // with hardcoded languages like ISO_8859_9. this.nGramLang = undefined; const ngrams = this.ngrams(); if (isFlatNgrams(ngrams)) { const parser = new NGramParser(ngrams, this.byteMap()); const confidence = parser.parse(det, this.spaceChar); return confidence <= 0 ? null : match(det, this, confidence); } let bestConfidence = -1; for (let i = ngrams.length - 1; i >= 0; i--) { const ngl = ngrams[i]; const parser = new NGramParser(ngl.fNGrams, this.byteMap()); const confidence = parser.parse(det, this.spaceChar); if (confidence > bestConfidence) { bestConfidence = confidence; this.nGramLang = ngl.fLang; } } return bestConfidence <= 0 ? null : match(det, this, bestConfidence); }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,953
name(input: Context): string { return input && input.c1Bytes ? 'windows-1252' : 'ISO-8859-1'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,954
name(det: Context): string { return det && det.c1Bytes ? 'windows-1250' : 'ISO-8859-2'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,955
name(det: Context): string { return det && det.c1Bytes ? 'windows-1253' : 'ISO-8859-7'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,956
name(det: Context): string { return det && det.c1Bytes ? 'windows-1255' : 'ISO-8859-8'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,957
name(det: Context): string { return det && det.c1Bytes ? 'windows-1254' : 'ISO-8859-9'; }
interface Context { byteStats: number[]; c1Bytes: boolean; rawInput: Uint8Array; rawLen: number; inputBytes: Uint8Array; inputLen: number; }
2,958
indexForLocation(location: SourceLocation): number | null { const { line, column } = location if (line < 0 || line >= this.offsets.length) { return null } if (column < 0 || column > this.lengthOfLine(line)) { return null } return this.offsets[line] + column }
interface SourceLocation { line: number column: number }
2,959
function makeTests(re: RegExp, testCase: Case): void { describe("matches", () => { for (const matchingCase of testCase.matching) { if (!ALL_FIXTURES.has(matchingCase)) { throw new Error( `fixture ${matchingCase.name} is missing from ALL_FIXTURES`); } it(matchingCase.name, () => { expect(re.test(matchingCase.data)).to.be.true; }); } }); describe("does not match", () => { for (const f of ALL_FIXTURES) { if (!testCase.matching.includes(f)) { it(f.name, () => { expect(re.test(f.data)).to.be.false; }); } } }); }
interface Case { matching: Fixture[]; }
2,960
function isGlobalType(n: Node): boolean;
type Node = false | NodeOptions;
2,961
function isTable(n: Node): boolean;
type Node = false | NodeOptions;
2,962
function isMemory(n: Node): boolean;
type Node = false | NodeOptions;
2,963
function isFuncImportDescr(n: Node): boolean;
type Node = false | NodeOptions;
2,964
map(options?: MapOptions): Object
type MapOptions = { columns?: boolean; module?: boolean };
2,965
map(options?: MapOptions): Object
interface MapOptions { columns?: boolean; module?: boolean; }
2,966
sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object; }
type MapOptions = { columns?: boolean; module?: boolean };
2,967
sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object; }
interface MapOptions { columns?: boolean; module?: boolean; }
2,968
constructor(source: Source, name?: string)
class Source { constructor(); size(): number; map(options?: MapOptions): Object; sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object }; updateHash(hash: Hash): void; source(): string | Buffer; buffer(): Buffer; }
2,969
constructor(source: Source)
class Source { constructor(); size(): number; map(options?: MapOptions): Object; sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object }; updateHash(hash: Hash): void; source(): string | Buffer; buffer(): Buffer; }
2,970
constructor(sourceLike: SourceLike)
interface SourceLike { source(): string | Buffer; }
2,971
static from(sourceLike: SourceLike): Source
interface SourceLike { source(): string | Buffer; }
2,972
(info: HotEvent) => void
type HotEvent = | { type: "disposed"; /** The module in question. */ moduleId: number; } | { type: "self-declined" | "unaccepted"; /** The module in question. */ moduleId: number; /** the chain from where the update was propagated. */ chain: number[]; } | { type: "declined"; /** The module in question. */ moduleId: number; /** the chain from where the update was propagated. */ chain: number[]; /** the module id of the declining parent */ parentId: number; } | { type: "accepted"; /** The module in question. */ moduleId: number; /** the chain from where the update was propagated. */ chain: number[]; /** the modules that are outdated and will be disposed */ outdatedModules: number[]; /** the accepted dependencies that are outdated */ outdatedDependencies: { [id: number]: number[]; }; } | { type: "accept-error-handler-errored"; /** The module in question. */ moduleId: number; /** the module id owning the accept handler. */ dependencyId: number; /** the thrown error */ error: Error; /** the error thrown by the module before the error handler tried to handle it. */ originalError: Error; } | { type: "self-accept-error-handler-errored"; /** The module in question. */ moduleId: number; /** the thrown error */ error: Error; /** the error thrown by the module before the error handler tried to handle it. */ originalError: Error; } | { type: "accept-errored"; /** The module in question. */ moduleId: number; /** the module id owning the accept handler. */ dependencyId: number; /** the thrown error */ error: Error; } | { type: "self-accept-errored"; /** The module in question. */ moduleId: number; /** the thrown error */ error: Error; };
2,973
apply(compiler: Compiler): void
class Compiler { constructor(context: string, options?: WebpackOptionsNormalized); hooks: Readonly<{ initialize: SyncHook<[]>; shouldEmit: SyncBailHook<[Compilation], boolean>; done: AsyncSeriesHook<[Stats]>; afterDone: SyncHook<[Stats]>; additionalPass: AsyncSeriesHook<[]>; beforeRun: AsyncSeriesHook<[Compiler]>; run: AsyncSeriesHook<[Compiler]>; emit: AsyncSeriesHook<[Compilation]>; assetEmitted: AsyncSeriesHook<[string, AssetEmittedInfo]>; afterEmit: AsyncSeriesHook<[Compilation]>; thisCompilation: SyncHook<[Compilation, CompilationParams]>; compilation: SyncHook<[Compilation, CompilationParams]>; normalModuleFactory: SyncHook<[NormalModuleFactory]>; contextModuleFactory: SyncHook<[ContextModuleFactory]>; beforeCompile: AsyncSeriesHook<[CompilationParams]>; compile: SyncHook<[CompilationParams]>; make: AsyncParallelHook<[Compilation]>; finishMake: AsyncParallelHook<[Compilation]>; afterCompile: AsyncSeriesHook<[Compilation]>; readRecords: AsyncSeriesHook<[]>; emitRecords: AsyncSeriesHook<[]>; watchRun: AsyncSeriesHook<[Compiler]>; failed: SyncHook<[Error]>; invalid: SyncHook<[null | string, number]>; watchClose: SyncHook<[]>; shutdown: AsyncSeriesHook<[]>; infrastructureLog: SyncBailHook<[string, string, any[]], true>; environment: SyncHook<[]>; afterEnvironment: SyncHook<[]>; afterPlugins: SyncHook<[Compiler]>; afterResolvers: SyncHook<[Compiler]>; entryOption: SyncBailHook<[string, EntryNormalized], boolean>; }>; webpack: typeof exports; name?: string; parentCompilation?: Compilation; root: Compiler; outputPath: string; watching: Watching; outputFileSystem: OutputFileSystem; intermediateFileSystem: IntermediateFileSystem; inputFileSystem: InputFileSystem; watchFileSystem: WatchFileSystem; recordsInputPath: null | string; recordsOutputPath: null | string; records: object; managedPaths: Set<string | RegExp>; immutablePaths: Set<string | RegExp>; modifiedFiles: ReadonlySet<string>; removedFiles: ReadonlySet<string>; fileTimestamps: ReadonlyMap<string, null | FileSystemInfoEntry | "ignore">; contextTimestamps: ReadonlyMap<string, null | FileSystemInfoEntry | "ignore">; fsStartTime: number; resolverFactory: ResolverFactory; infrastructureLogger: any; options: WebpackOptionsNormalized; context: string; requestShortener: RequestShortener; cache: Cache; moduleMemCaches?: Map< Module, { buildInfo: object; references: WeakMap<Dependency, Module>; memCache: WeakTupleMap<any, any>; } >; compilerPath: string; running: boolean; idle: boolean; watchMode: boolean; getCache(name: string): CacheFacade; getInfrastructureLogger(name: string | (() => string)): WebpackLogger; watch(watchOptions: WatchOptions, handler: CallbackFunction<Stats>): Watching; run(callback: CallbackFunction<Stats>): void; runAsChild( callback: ( err?: null | Error, entries?: Chunk[], compilation?: Compilation ) => any ): void; purgeInputFileSystem(): void; emitAssets(compilation: Compilation, callback: CallbackFunction<void>): void; emitRecords(callback: CallbackFunction<void>): void; readRecords(callback: CallbackFunction<void>): void; createChildCompiler( compilation: Compilation, compilerName: string, compilerIndex: number, outputOptions?: OutputNormalized, plugins?: WebpackPluginInstance[] ): Compiler; isChild(): boolean; createCompilation(params?: any): Compilation; newCompilation(params: CompilationParams): Compilation; createNormalModuleFactory(): NormalModuleFactory; createContextModuleFactory(): ContextModuleFactory; newCompilationParams(): { normalModuleFactory: NormalModuleFactory; contextModuleFactory: ContextModuleFactory; }; compile(callback: CallbackFunction<Compilation>): void; close(callback: CallbackFunction<void>): void; }
2,974
parseOptions(library: LibraryOptions): false | T
interface LibraryOptions { /** * Add a comment in the UMD wrapper. */ auxiliaryComment?: string | LibraryCustomUmdCommentObject; /** * Specify which export should be exposed as library. */ export?: string | string[]; /** * The name of the library (some types allow unnamed libraries too). */ name?: string | string[] | LibraryCustomUmdObject; /** * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins). */ type: string; /** * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module. */ umdNamedDefine?: boolean; }
2,975
parseOptions(library: LibraryOptions): false | T
interface LibraryOptions { /** * Add a comment in the UMD wrapper. */ auxiliaryComment?: AuxiliaryComment; /** * Specify which export should be exposed as library. */ export?: LibraryExport; /** * The name of the library (some types allow unnamed libraries too). */ name?: LibraryName; /** * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins). */ type: LibraryType; /** * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module. */ umdNamedDefine?: UmdNamedDefine; }
2,976
parseOptions(library: LibraryOptions): false | T
interface LibraryOptions { /** * Add a comment in the UMD wrapper. */ auxiliaryComment?: AuxiliaryComment; /** * Specify which export should be exposed as library. */ export?: LibraryExport; /** * The name of the library (some types allow unnamed libraries too). */ name?: LibraryName; /** * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins). */ type: LibraryType; /** * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module. */ umdNamedDefine?: UmdNamedDefine; }
2,977
parseOptions(library: LibraryOptions): false | T
interface LibraryOptions { /** * Add a comment in the UMD wrapper. */ auxiliaryComment?: AuxiliaryComment; /** * Specify which export should be exposed as library. */ export?: LibraryExport; /** * The name of the library (some types allow unnamed libraries too). */ name?: LibraryName; /** * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins). */ type: LibraryType; /** * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module. */ umdNamedDefine?: UmdNamedDefine; }
2,978
finishEntryModule( module: Module, entryName: string, libraryContext: LibraryContext<T> ): void
interface Module { hot: webpack.Hot; }
2,979
finishEntryModule( module: Module, entryName: string, libraryContext: LibraryContext<T> ): void
class Module extends DependenciesBlock { constructor(type: string, context?: string, layer?: string); type: string; context: null | string; layer: null | string; needId: boolean; debugId: number; resolveOptions: ResolveOptionsWebpackOptions; factoryMeta?: object; useSourceMap: boolean; useSimpleSourceMap: boolean; buildMeta: BuildMeta; buildInfo: Record<string, any>; presentationalDependencies?: Dependency[]; codeGenerationDependencies?: Dependency[]; id: string | number; get hash(): string; get renderedHash(): string; profile: null | ModuleProfile; index: number; index2: number; depth: number; issuer: null | Module; get usedExports(): null | boolean | SortableSet<string>; get optimizationBailout(): ( | string | ((requestShortener: RequestShortener) => string) )[]; get optional(): boolean; addChunk(chunk?: any): boolean; removeChunk(chunk?: any): void; isInChunk(chunk?: any): boolean; isEntryModule(): boolean; getChunks(): Chunk[]; getNumberOfChunks(): number; get chunksIterable(): Iterable<Chunk>; isProvided(exportName: string): null | boolean; get exportsArgument(): string; get moduleArgument(): string; getExportsType( moduleGraph: ModuleGraph, strict: boolean ): "namespace" | "default-only" | "default-with-named" | "dynamic"; addPresentationalDependency(presentationalDependency: Dependency): void; addCodeGenerationDependency(codeGenerationDependency: Dependency): void; addWarning(warning: WebpackError): void; getWarnings(): undefined | Iterable<WebpackError>; getNumberOfWarnings(): number; addError(error: WebpackError): void; getErrors(): undefined | Iterable<WebpackError>; getNumberOfErrors(): number; /** * removes all warnings and errors */ clearWarningsAndErrors(): void; isOptional(moduleGraph: ModuleGraph): boolean; isAccessibleInChunk( chunkGraph: ChunkGraph, chunk: Chunk, ignoreChunk?: Chunk ): boolean; isAccessibleInChunkGroup( chunkGraph: ChunkGraph, chunkGroup: ChunkGroup, ignoreChunk?: Chunk ): boolean; hasReasonForChunk( chunk: Chunk, moduleGraph: ModuleGraph, chunkGraph: ChunkGraph ): boolean; hasReasons(moduleGraph: ModuleGraph, runtime: RuntimeSpec): boolean; needBuild( context: NeedBuildContext, callback: (arg0?: null | WebpackError, arg1?: boolean) => void ): void; needRebuild( fileTimestamps: Map<string, null | number>, contextTimestamps: Map<string, null | number> ): boolean; invalidateBuild(): void; identifier(): string; readableIdentifier(requestShortener: RequestShortener): string; build( options: WebpackOptionsNormalized, compilation: Compilation, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (arg0?: WebpackError) => void ): void; getSourceTypes(): Set<string>; source( dependencyTemplates: DependencyTemplates, runtimeTemplate: RuntimeTemplate, type?: string ): Source; size(type?: string): number; libIdent(options: LibIdentOptions): null | string; nameForCondition(): null | string; getConcatenationBailoutReason( context: ConcatenationBailoutReasonContext ): undefined | string; getSideEffectsConnectionState(moduleGraph: ModuleGraph): ConnectionState; codeGeneration(context: CodeGenerationContext): CodeGenerationResult; chunkCondition(chunk: Chunk, compilation: Compilation): boolean; hasChunkCondition(): boolean; /** * Assuming this module is in the cache. Update the (cached) module with * the fresh module from the factory. Usually updates internal references * and properties. */ updateCacheModule(module: Module): void; /** * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. */ getUnsafeCacheData(): object; /** * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ cleanupForCache(): void; originalSource(): null | Source; addCacheDependencies( fileDependencies: LazySet<string>, contextDependencies: LazySet<string>, missingDependencies: LazySet<string>, buildDependencies: LazySet<string> ): void; get hasEqualsChunks(): any; get isUsed(): any; get errors(): any; get warnings(): any; used: any; }
2,980
embedInRuntimeBailout( module: Module, renderContext: RenderContext, libraryContext: LibraryContext<T> ): undefined | string
interface RenderContext { /** * the chunk */ chunk: Chunk; /** * the dependency templates */ dependencyTemplates: DependencyTemplates; /** * the runtime template */ runtimeTemplate: RuntimeTemplate; /** * the module graph */ moduleGraph: ModuleGraph; /** * the chunk graph */ chunkGraph: ChunkGraph; /** * results of code generation */ codeGenerationResults: CodeGenerationResults; /** * rendering in strict context */ strictMode: boolean; }
2,981
embedInRuntimeBailout( module: Module, renderContext: RenderContext, libraryContext: LibraryContext<T> ): undefined | string
interface Module { hot: webpack.Hot; }
2,982
embedInRuntimeBailout( module: Module, renderContext: RenderContext, libraryContext: LibraryContext<T> ): undefined | string
class Module extends DependenciesBlock { constructor(type: string, context?: string, layer?: string); type: string; context: null | string; layer: null | string; needId: boolean; debugId: number; resolveOptions: ResolveOptionsWebpackOptions; factoryMeta?: object; useSourceMap: boolean; useSimpleSourceMap: boolean; buildMeta: BuildMeta; buildInfo: Record<string, any>; presentationalDependencies?: Dependency[]; codeGenerationDependencies?: Dependency[]; id: string | number; get hash(): string; get renderedHash(): string; profile: null | ModuleProfile; index: number; index2: number; depth: number; issuer: null | Module; get usedExports(): null | boolean | SortableSet<string>; get optimizationBailout(): ( | string | ((requestShortener: RequestShortener) => string) )[]; get optional(): boolean; addChunk(chunk?: any): boolean; removeChunk(chunk?: any): void; isInChunk(chunk?: any): boolean; isEntryModule(): boolean; getChunks(): Chunk[]; getNumberOfChunks(): number; get chunksIterable(): Iterable<Chunk>; isProvided(exportName: string): null | boolean; get exportsArgument(): string; get moduleArgument(): string; getExportsType( moduleGraph: ModuleGraph, strict: boolean ): "namespace" | "default-only" | "default-with-named" | "dynamic"; addPresentationalDependency(presentationalDependency: Dependency): void; addCodeGenerationDependency(codeGenerationDependency: Dependency): void; addWarning(warning: WebpackError): void; getWarnings(): undefined | Iterable<WebpackError>; getNumberOfWarnings(): number; addError(error: WebpackError): void; getErrors(): undefined | Iterable<WebpackError>; getNumberOfErrors(): number; /** * removes all warnings and errors */ clearWarningsAndErrors(): void; isOptional(moduleGraph: ModuleGraph): boolean; isAccessibleInChunk( chunkGraph: ChunkGraph, chunk: Chunk, ignoreChunk?: Chunk ): boolean; isAccessibleInChunkGroup( chunkGraph: ChunkGraph, chunkGroup: ChunkGroup, ignoreChunk?: Chunk ): boolean; hasReasonForChunk( chunk: Chunk, moduleGraph: ModuleGraph, chunkGraph: ChunkGraph ): boolean; hasReasons(moduleGraph: ModuleGraph, runtime: RuntimeSpec): boolean; needBuild( context: NeedBuildContext, callback: (arg0?: null | WebpackError, arg1?: boolean) => void ): void; needRebuild( fileTimestamps: Map<string, null | number>, contextTimestamps: Map<string, null | number> ): boolean; invalidateBuild(): void; identifier(): string; readableIdentifier(requestShortener: RequestShortener): string; build( options: WebpackOptionsNormalized, compilation: Compilation, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (arg0?: WebpackError) => void ): void; getSourceTypes(): Set<string>; source( dependencyTemplates: DependencyTemplates, runtimeTemplate: RuntimeTemplate, type?: string ): Source; size(type?: string): number; libIdent(options: LibIdentOptions): null | string; nameForCondition(): null | string; getConcatenationBailoutReason( context: ConcatenationBailoutReasonContext ): undefined | string; getSideEffectsConnectionState(moduleGraph: ModuleGraph): ConnectionState; codeGeneration(context: CodeGenerationContext): CodeGenerationResult; chunkCondition(chunk: Chunk, compilation: Compilation): boolean; hasChunkCondition(): boolean; /** * Assuming this module is in the cache. Update the (cached) module with * the fresh module from the factory. Usually updates internal references * and properties. */ updateCacheModule(module: Module): void; /** * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. */ getUnsafeCacheData(): object; /** * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ cleanupForCache(): void; originalSource(): null | Source; addCacheDependencies( fileDependencies: LazySet<string>, contextDependencies: LazySet<string>, missingDependencies: LazySet<string>, buildDependencies: LazySet<string> ): void; get hasEqualsChunks(): any; get isUsed(): any; get errors(): any; get warnings(): any; used: any; }
2,983
strictRuntimeBailout( renderContext: RenderContext, libraryContext: LibraryContext<T> ): undefined | string
interface RenderContext { /** * the chunk */ chunk: Chunk; /** * the dependency templates */ dependencyTemplates: DependencyTemplates; /** * the runtime template */ runtimeTemplate: RuntimeTemplate; /** * the module graph */ moduleGraph: ModuleGraph; /** * the chunk graph */ chunkGraph: ChunkGraph; /** * results of code generation */ codeGenerationResults: CodeGenerationResults; /** * rendering in strict context */ strictMode: boolean; }
2,984
runtimeRequirements( chunk: Chunk, set: Set<string>, libraryContext: LibraryContext<T> ): void
class Chunk { constructor(name?: string, backCompat?: boolean); id: null | string | number; ids: null | (string | number)[]; debugId: number; name: string; idNameHints: SortableSet<string>; preventIntegration: boolean; filenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); cssFilenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); runtime: RuntimeSpec; files: Set<string>; auxiliaryFiles: Set<string>; rendered: boolean; hash?: string; contentHash: Record<string, string>; renderedHash?: string; chunkReason?: string; extraAsync: boolean; get entryModule(): Module; hasEntryModule(): boolean; addModule(module: Module): boolean; removeModule(module: Module): void; getNumberOfModules(): number; get modulesIterable(): Iterable<Module>; compareTo(otherChunk: Chunk): 0 | 1 | -1; containsModule(module: Module): boolean; getModules(): Module[]; remove(): void; moveModule(module: Module, otherChunk: Chunk): void; integrate(otherChunk: Chunk): boolean; canBeIntegrated(otherChunk: Chunk): boolean; isEmpty(): boolean; modulesSize(): number; size(options?: ChunkSizeOptions): number; integratedSize(otherChunk: Chunk, options: ChunkSizeOptions): number; getChunkModuleMaps(filterFn: (m: Module) => boolean): ChunkModuleMaps; hasModuleInGraph( filterFn: (m: Module) => boolean, filterChunkFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): boolean; getChunkMaps(realHash: boolean): ChunkMaps; hasRuntime(): boolean; canBeInitial(): boolean; isOnlyInitial(): boolean; getEntryOptions(): undefined | EntryOptions; addGroup(chunkGroup: ChunkGroup): void; removeGroup(chunkGroup: ChunkGroup): void; isInGroup(chunkGroup: ChunkGroup): boolean; getNumberOfGroups(): number; get groupsIterable(): Iterable<ChunkGroup>; disconnectFromGroups(): void; split(newChunk: Chunk): void; updateHash(hash: Hash, chunkGraph: ChunkGraph): void; getAllAsyncChunks(): Set<Chunk>; getAllInitialChunks(): Set<Chunk>; getAllReferencedChunks(): Set<Chunk>; getAllReferencedAsyncEntrypoints(): Set<Entrypoint>; hasAsyncChunks(): boolean; getChildIdsByOrders( chunkGraph: ChunkGraph, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string, (string | number)[]>; getChildrenOfTypeInOrder( chunkGraph: ChunkGraph, type: string ): { onChunks: Chunk[]; chunks: Set<Chunk> }[]; getChildIdsByOrdersMap( chunkGraph: ChunkGraph, includeDirectChildren?: boolean, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string | number, Record<string, (string | number)[]>>; }
2,985
render( source: Source, renderContext: RenderContext, libraryContext: LibraryContext<T> ): Source
interface RenderContext { /** * the chunk */ chunk: Chunk; /** * the dependency templates */ dependencyTemplates: DependencyTemplates; /** * the runtime template */ runtimeTemplate: RuntimeTemplate; /** * the module graph */ moduleGraph: ModuleGraph; /** * the chunk graph */ chunkGraph: ChunkGraph; /** * results of code generation */ codeGenerationResults: CodeGenerationResults; /** * rendering in strict context */ strictMode: boolean; }
2,986
render( source: Source, renderContext: RenderContext, libraryContext: LibraryContext<T> ): Source
class Source { constructor(); size(): number; map(options?: MapOptions): Object; sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object }; updateHash(hash: Hash): void; source(): string | Buffer; buffer(): Buffer; }
2,987
renderStartup( source: Source, module: Module, renderContext: StartupRenderContext, libraryContext: LibraryContext<T> ): Source
type StartupRenderContext = RenderContext & { inlined: boolean };
2,988
renderStartup( source: Source, module: Module, renderContext: StartupRenderContext, libraryContext: LibraryContext<T> ): Source
interface Module { hot: webpack.Hot; }
2,989
renderStartup( source: Source, module: Module, renderContext: StartupRenderContext, libraryContext: LibraryContext<T> ): Source
class Module extends DependenciesBlock { constructor(type: string, context?: string, layer?: string); type: string; context: null | string; layer: null | string; needId: boolean; debugId: number; resolveOptions: ResolveOptionsWebpackOptions; factoryMeta?: object; useSourceMap: boolean; useSimpleSourceMap: boolean; buildMeta: BuildMeta; buildInfo: Record<string, any>; presentationalDependencies?: Dependency[]; codeGenerationDependencies?: Dependency[]; id: string | number; get hash(): string; get renderedHash(): string; profile: null | ModuleProfile; index: number; index2: number; depth: number; issuer: null | Module; get usedExports(): null | boolean | SortableSet<string>; get optimizationBailout(): ( | string | ((requestShortener: RequestShortener) => string) )[]; get optional(): boolean; addChunk(chunk?: any): boolean; removeChunk(chunk?: any): void; isInChunk(chunk?: any): boolean; isEntryModule(): boolean; getChunks(): Chunk[]; getNumberOfChunks(): number; get chunksIterable(): Iterable<Chunk>; isProvided(exportName: string): null | boolean; get exportsArgument(): string; get moduleArgument(): string; getExportsType( moduleGraph: ModuleGraph, strict: boolean ): "namespace" | "default-only" | "default-with-named" | "dynamic"; addPresentationalDependency(presentationalDependency: Dependency): void; addCodeGenerationDependency(codeGenerationDependency: Dependency): void; addWarning(warning: WebpackError): void; getWarnings(): undefined | Iterable<WebpackError>; getNumberOfWarnings(): number; addError(error: WebpackError): void; getErrors(): undefined | Iterable<WebpackError>; getNumberOfErrors(): number; /** * removes all warnings and errors */ clearWarningsAndErrors(): void; isOptional(moduleGraph: ModuleGraph): boolean; isAccessibleInChunk( chunkGraph: ChunkGraph, chunk: Chunk, ignoreChunk?: Chunk ): boolean; isAccessibleInChunkGroup( chunkGraph: ChunkGraph, chunkGroup: ChunkGroup, ignoreChunk?: Chunk ): boolean; hasReasonForChunk( chunk: Chunk, moduleGraph: ModuleGraph, chunkGraph: ChunkGraph ): boolean; hasReasons(moduleGraph: ModuleGraph, runtime: RuntimeSpec): boolean; needBuild( context: NeedBuildContext, callback: (arg0?: null | WebpackError, arg1?: boolean) => void ): void; needRebuild( fileTimestamps: Map<string, null | number>, contextTimestamps: Map<string, null | number> ): boolean; invalidateBuild(): void; identifier(): string; readableIdentifier(requestShortener: RequestShortener): string; build( options: WebpackOptionsNormalized, compilation: Compilation, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (arg0?: WebpackError) => void ): void; getSourceTypes(): Set<string>; source( dependencyTemplates: DependencyTemplates, runtimeTemplate: RuntimeTemplate, type?: string ): Source; size(type?: string): number; libIdent(options: LibIdentOptions): null | string; nameForCondition(): null | string; getConcatenationBailoutReason( context: ConcatenationBailoutReasonContext ): undefined | string; getSideEffectsConnectionState(moduleGraph: ModuleGraph): ConnectionState; codeGeneration(context: CodeGenerationContext): CodeGenerationResult; chunkCondition(chunk: Chunk, compilation: Compilation): boolean; hasChunkCondition(): boolean; /** * Assuming this module is in the cache. Update the (cached) module with * the fresh module from the factory. Usually updates internal references * and properties. */ updateCacheModule(module: Module): void; /** * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. */ getUnsafeCacheData(): object; /** * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ cleanupForCache(): void; originalSource(): null | Source; addCacheDependencies( fileDependencies: LazySet<string>, contextDependencies: LazySet<string>, missingDependencies: LazySet<string>, buildDependencies: LazySet<string> ): void; get hasEqualsChunks(): any; get isUsed(): any; get errors(): any; get warnings(): any; used: any; }
2,990
renderStartup( source: Source, module: Module, renderContext: StartupRenderContext, libraryContext: LibraryContext<T> ): Source
class Source { constructor(); size(): number; map(options?: MapOptions): Object; sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object }; updateHash(hash: Hash): void; source(): string | Buffer; buffer(): Buffer; }
2,991
chunkHash( chunk: Chunk, hash: Hash, chunkHashContext: ChunkHashContext, libraryContext: LibraryContext<T> ): void
interface ChunkHashContext { /** * results of code generation */ codeGenerationResults: CodeGenerationResults; /** * the runtime template */ runtimeTemplate: RuntimeTemplate; /** * the module graph */ moduleGraph: ModuleGraph; /** * the chunk graph */ chunkGraph: ChunkGraph; }
2,992
chunkHash( chunk: Chunk, hash: Hash, chunkHashContext: ChunkHashContext, libraryContext: LibraryContext<T> ): void
class Hash { constructor(); /** * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} */ update(data: string | Buffer, inputEncoding?: string): Hash; /** * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} */ digest(encoding?: string): string | Buffer; }
2,993
chunkHash( chunk: Chunk, hash: Hash, chunkHashContext: ChunkHashContext, libraryContext: LibraryContext<T> ): void
class Chunk { constructor(name?: string, backCompat?: boolean); id: null | string | number; ids: null | (string | number)[]; debugId: number; name: string; idNameHints: SortableSet<string>; preventIntegration: boolean; filenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); cssFilenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); runtime: RuntimeSpec; files: Set<string>; auxiliaryFiles: Set<string>; rendered: boolean; hash?: string; contentHash: Record<string, string>; renderedHash?: string; chunkReason?: string; extraAsync: boolean; get entryModule(): Module; hasEntryModule(): boolean; addModule(module: Module): boolean; removeModule(module: Module): void; getNumberOfModules(): number; get modulesIterable(): Iterable<Module>; compareTo(otherChunk: Chunk): 0 | 1 | -1; containsModule(module: Module): boolean; getModules(): Module[]; remove(): void; moveModule(module: Module, otherChunk: Chunk): void; integrate(otherChunk: Chunk): boolean; canBeIntegrated(otherChunk: Chunk): boolean; isEmpty(): boolean; modulesSize(): number; size(options?: ChunkSizeOptions): number; integratedSize(otherChunk: Chunk, options: ChunkSizeOptions): number; getChunkModuleMaps(filterFn: (m: Module) => boolean): ChunkModuleMaps; hasModuleInGraph( filterFn: (m: Module) => boolean, filterChunkFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): boolean; getChunkMaps(realHash: boolean): ChunkMaps; hasRuntime(): boolean; canBeInitial(): boolean; isOnlyInitial(): boolean; getEntryOptions(): undefined | EntryOptions; addGroup(chunkGroup: ChunkGroup): void; removeGroup(chunkGroup: ChunkGroup): void; isInGroup(chunkGroup: ChunkGroup): boolean; getNumberOfGroups(): number; get groupsIterable(): Iterable<ChunkGroup>; disconnectFromGroups(): void; split(newChunk: Chunk): void; updateHash(hash: Hash, chunkGraph: ChunkGraph): void; getAllAsyncChunks(): Set<Chunk>; getAllInitialChunks(): Set<Chunk>; getAllReferencedChunks(): Set<Chunk>; getAllReferencedAsyncEntrypoints(): Set<Entrypoint>; hasAsyncChunks(): boolean; getChildIdsByOrders( chunkGraph: ChunkGraph, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string, (string | number)[]>; getChildrenOfTypeInOrder( chunkGraph: ChunkGraph, type: string ): { onChunks: Chunk[]; chunks: Set<Chunk> }[]; getChildIdsByOrdersMap( chunkGraph: ChunkGraph, includeDirectChildren?: boolean, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string | number, Record<string, (string | number)[]>>; }
2,994
constructor(options?: AggressiveSplittingPluginOptions)
interface AggressiveSplittingPluginOptions { /** * Extra cost for each chunk (Default: 9.8kiB). */ chunkOverhead?: number; /** * Extra cost multiplicator for entry chunks (Default: 10). */ entryChunkMultiplicator?: number; /** * Byte, max size of per file (Default: 50kiB). */ maxSize?: number; /** * Byte, split point. (Default: 30kiB). */ minSize?: number; }
2,995
constructor(options?: AggressiveSplittingPluginOptions)
interface AggressiveSplittingPluginOptions { /** * Extra cost for each chunk (Default: 9.8kiB). */ chunkOverhead?: number; /** * Extra cost multiplicator for entry chunks (Default: 10). */ entryChunkMultiplicator?: number; /** * Byte, max size of per file (Default: 50kiB). */ maxSize?: number; /** * Byte, split point. (Default: 30kiB). */ minSize?: number; }
2,996
static wasChunkRecorded(chunk: Chunk): boolean
class Chunk { constructor(name?: string, backCompat?: boolean); id: null | string | number; ids: null | (string | number)[]; debugId: number; name: string; idNameHints: SortableSet<string>; preventIntegration: boolean; filenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); cssFilenameTemplate: | null | string | ((arg0: PathData, arg1?: AssetInfo) => string); runtime: RuntimeSpec; files: Set<string>; auxiliaryFiles: Set<string>; rendered: boolean; hash?: string; contentHash: Record<string, string>; renderedHash?: string; chunkReason?: string; extraAsync: boolean; get entryModule(): Module; hasEntryModule(): boolean; addModule(module: Module): boolean; removeModule(module: Module): void; getNumberOfModules(): number; get modulesIterable(): Iterable<Module>; compareTo(otherChunk: Chunk): 0 | 1 | -1; containsModule(module: Module): boolean; getModules(): Module[]; remove(): void; moveModule(module: Module, otherChunk: Chunk): void; integrate(otherChunk: Chunk): boolean; canBeIntegrated(otherChunk: Chunk): boolean; isEmpty(): boolean; modulesSize(): number; size(options?: ChunkSizeOptions): number; integratedSize(otherChunk: Chunk, options: ChunkSizeOptions): number; getChunkModuleMaps(filterFn: (m: Module) => boolean): ChunkModuleMaps; hasModuleInGraph( filterFn: (m: Module) => boolean, filterChunkFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): boolean; getChunkMaps(realHash: boolean): ChunkMaps; hasRuntime(): boolean; canBeInitial(): boolean; isOnlyInitial(): boolean; getEntryOptions(): undefined | EntryOptions; addGroup(chunkGroup: ChunkGroup): void; removeGroup(chunkGroup: ChunkGroup): void; isInGroup(chunkGroup: ChunkGroup): boolean; getNumberOfGroups(): number; get groupsIterable(): Iterable<ChunkGroup>; disconnectFromGroups(): void; split(newChunk: Chunk): void; updateHash(hash: Hash, chunkGraph: ChunkGraph): void; getAllAsyncChunks(): Set<Chunk>; getAllInitialChunks(): Set<Chunk>; getAllReferencedChunks(): Set<Chunk>; getAllReferencedAsyncEntrypoints(): Set<Entrypoint>; hasAsyncChunks(): boolean; getChildIdsByOrders( chunkGraph: ChunkGraph, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string, (string | number)[]>; getChildrenOfTypeInOrder( chunkGraph: ChunkGraph, type: string ): { onChunks: Chunk[]; chunks: Set<Chunk> }[]; getChildIdsByOrdersMap( chunkGraph: ChunkGraph, includeDirectChildren?: boolean, filterFn?: (c: Chunk, chunkGraph: ChunkGraph) => boolean ): Record<string | number, Record<string, (string | number)[]>>; }
2,997
(pathData: PathData, assetInfo?: AssetInfo) => string
interface PathData { chunkGraph?: ChunkGraph; hash?: string; hashWithLength?: (arg0: number) => string; chunk?: Chunk | ChunkPathData; module?: Module | ModulePathData; runtime?: RuntimeSpec; filename?: string; basename?: string; query?: string; contentHashType?: string; contentHash?: string; contentHashWithLength?: (arg0: number) => string; noChunkHash?: boolean; url?: string; }
2,998
(pathData: PathData, assetInfo?: AssetInfo) => string
type AssetInfo = KnownAssetInfo & Record<string, any>;
2,999
static getCompilationHooks( compilation: Compilation ): CompilationHooksAsyncWebAssemblyModulesPlugin
class Compilation { /** * Creates an instance of Compilation. */ constructor(compiler: Compiler, params: CompilationParams); hooks: Readonly<{ buildModule: SyncHook<[Module]>; rebuildModule: SyncHook<[Module]>; failedModule: SyncHook<[Module, WebpackError]>; succeedModule: SyncHook<[Module]>; stillValidModule: SyncHook<[Module]>; addEntry: SyncHook<[Dependency, EntryOptions]>; failedEntry: SyncHook<[Dependency, EntryOptions, Error]>; succeedEntry: SyncHook<[Dependency, EntryOptions, Module]>; dependencyReferencedExports: SyncWaterfallHook< [(string[] | ReferencedExport)[], Dependency, RuntimeSpec] >; executeModule: SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>; prepareModuleExecution: AsyncParallelHook< [ExecuteModuleArgument, ExecuteModuleContext] >; finishModules: AsyncSeriesHook<[Iterable<Module>]>; finishRebuildingModule: AsyncSeriesHook<[Module]>; unseal: SyncHook<[]>; seal: SyncHook<[]>; beforeChunks: SyncHook<[]>; afterChunks: SyncHook<[Iterable<Chunk>]>; optimizeDependencies: SyncBailHook<[Iterable<Module>], any>; afterOptimizeDependencies: SyncHook<[Iterable<Module>]>; optimize: SyncHook<[]>; optimizeModules: SyncBailHook<[Iterable<Module>], any>; afterOptimizeModules: SyncHook<[Iterable<Module>]>; optimizeChunks: SyncBailHook<[Iterable<Chunk>, ChunkGroup[]], any>; afterOptimizeChunks: SyncHook<[Iterable<Chunk>, ChunkGroup[]]>; optimizeTree: AsyncSeriesHook<[Iterable<Chunk>, Iterable<Module>]>; afterOptimizeTree: SyncHook<[Iterable<Chunk>, Iterable<Module>]>; optimizeChunkModules: AsyncSeriesBailHook< [Iterable<Chunk>, Iterable<Module>], any >; afterOptimizeChunkModules: SyncHook<[Iterable<Chunk>, Iterable<Module>]>; shouldRecord: SyncBailHook<[], boolean>; additionalChunkRuntimeRequirements: SyncHook< [Chunk, Set<string>, RuntimeRequirementsContext] >; runtimeRequirementInChunk: HookMap< SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], any> >; additionalModuleRuntimeRequirements: SyncHook< [Module, Set<string>, RuntimeRequirementsContext] >; runtimeRequirementInModule: HookMap< SyncBailHook<[Module, Set<string>, RuntimeRequirementsContext], any> >; additionalTreeRuntimeRequirements: SyncHook< [Chunk, Set<string>, RuntimeRequirementsContext] >; runtimeRequirementInTree: HookMap< SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], any> >; runtimeModule: SyncHook<[RuntimeModule, Chunk]>; reviveModules: SyncHook<[Iterable<Module>, any]>; beforeModuleIds: SyncHook<[Iterable<Module>]>; moduleIds: SyncHook<[Iterable<Module>]>; optimizeModuleIds: SyncHook<[Iterable<Module>]>; afterOptimizeModuleIds: SyncHook<[Iterable<Module>]>; reviveChunks: SyncHook<[Iterable<Chunk>, any]>; beforeChunkIds: SyncHook<[Iterable<Chunk>]>; chunkIds: SyncHook<[Iterable<Chunk>]>; optimizeChunkIds: SyncHook<[Iterable<Chunk>]>; afterOptimizeChunkIds: SyncHook<[Iterable<Chunk>]>; recordModules: SyncHook<[Iterable<Module>, any]>; recordChunks: SyncHook<[Iterable<Chunk>, any]>; optimizeCodeGeneration: SyncHook<[Iterable<Module>]>; beforeModuleHash: SyncHook<[]>; afterModuleHash: SyncHook<[]>; beforeCodeGeneration: SyncHook<[]>; afterCodeGeneration: SyncHook<[]>; beforeRuntimeRequirements: SyncHook<[]>; afterRuntimeRequirements: SyncHook<[]>; beforeHash: SyncHook<[]>; contentHash: SyncHook<[Chunk]>; afterHash: SyncHook<[]>; recordHash: SyncHook<[any]>; record: SyncHook<[Compilation, any]>; beforeModuleAssets: SyncHook<[]>; shouldGenerateChunkAssets: SyncBailHook<[], boolean>; beforeChunkAssets: SyncHook<[]>; additionalChunkAssets: FakeHook< Pick< AsyncSeriesHook<[Set<Chunk>]>, "name" | "tap" | "tapAsync" | "tapPromise" > >; additionalAssets: FakeHook< Pick<AsyncSeriesHook<[]>, "name" | "tap" | "tapAsync" | "tapPromise"> >; optimizeChunkAssets: FakeHook< Pick< AsyncSeriesHook<[Set<Chunk>]>, "name" | "tap" | "tapAsync" | "tapPromise" > >; afterOptimizeChunkAssets: FakeHook< Pick< AsyncSeriesHook<[Set<Chunk>]>, "name" | "tap" | "tapAsync" | "tapPromise" > >; optimizeAssets: AsyncSeriesHook< [CompilationAssets], ProcessAssetsAdditionalOptions >; afterOptimizeAssets: SyncHook<[CompilationAssets]>; processAssets: AsyncSeriesHook< [CompilationAssets], ProcessAssetsAdditionalOptions >; afterProcessAssets: SyncHook<[CompilationAssets]>; processAdditionalAssets: AsyncSeriesHook<[CompilationAssets]>; needAdditionalSeal: SyncBailHook<[], boolean>; afterSeal: AsyncSeriesHook<[]>; renderManifest: SyncWaterfallHook< [RenderManifestEntry[], RenderManifestOptions] >; fullHash: SyncHook<[Hash]>; chunkHash: SyncHook<[Chunk, Hash, ChunkHashContext]>; moduleAsset: SyncHook<[Module, string]>; chunkAsset: SyncHook<[Chunk, string]>; assetPath: SyncWaterfallHook<[string, object, AssetInfo]>; needAdditionalPass: SyncBailHook<[], boolean>; childCompiler: SyncHook<[Compiler, string, number]>; log: SyncBailHook<[string, LogEntry], true>; processWarnings: SyncWaterfallHook<[WebpackError[]]>; processErrors: SyncWaterfallHook<[WebpackError[]]>; statsPreset: HookMap< SyncHook<[Partial<NormalizedStatsOptions>, CreateStatsOptionsContext]> >; statsNormalize: SyncHook< [Partial<NormalizedStatsOptions>, CreateStatsOptionsContext] >; statsFactory: SyncHook<[StatsFactory, NormalizedStatsOptions]>; statsPrinter: SyncHook<[StatsPrinter, NormalizedStatsOptions]>; get normalModuleLoader(): SyncHook<[object, NormalModule]>; }>; name?: string; startTime: any; endTime: any; compiler: Compiler; resolverFactory: ResolverFactory; inputFileSystem: InputFileSystem; fileSystemInfo: FileSystemInfo; valueCacheVersions: Map<string, string | Set<string>>; requestShortener: RequestShortener; compilerPath: string; logger: WebpackLogger; options: WebpackOptionsNormalized; outputOptions: OutputNormalized; bail: boolean; profile: boolean; params: CompilationParams; mainTemplate: MainTemplate; chunkTemplate: ChunkTemplate; runtimeTemplate: RuntimeTemplate; moduleTemplates: { javascript: ModuleTemplate }; moduleMemCaches?: Map<Module, WeakTupleMap<any, any>>; moduleMemCaches2?: Map<Module, WeakTupleMap<any, any>>; moduleGraph: ModuleGraph; chunkGraph: ChunkGraph; codeGenerationResults: CodeGenerationResults; processDependenciesQueue: AsyncQueue<Module, Module, Module>; addModuleQueue: AsyncQueue<Module, string, Module>; factorizeQueue: AsyncQueue< FactorizeModuleOptions, string, Module | ModuleFactoryResult >; buildQueue: AsyncQueue<Module, Module, Module>; rebuildQueue: AsyncQueue<Module, Module, Module>; /** * Modules in value are building during the build of Module in key. * Means value blocking key from finishing. * Needed to detect build cycles. */ creatingModuleDuringBuild: WeakMap<Module, Set<Module>>; entries: Map<string, EntryData>; globalEntry: EntryData; entrypoints: Map<string, Entrypoint>; asyncEntrypoints: Entrypoint[]; chunks: Set<Chunk>; chunkGroups: ChunkGroup[]; namedChunkGroups: Map<string, ChunkGroup>; namedChunks: Map<string, Chunk>; modules: Set<Module>; records: any; additionalChunkAssets: string[]; assets: CompilationAssets; assetsInfo: Map<string, AssetInfo>; errors: WebpackError[]; warnings: WebpackError[]; children: Compilation[]; logging: Map<string, LogEntry[]>; dependencyFactories: Map<DepConstructor, ModuleFactory>; dependencyTemplates: DependencyTemplates; childrenCounters: object; usedChunkIds: Set<string | number>; usedModuleIds: Set<number>; needAdditionalPass: boolean; builtModules: WeakSet<Module>; codeGeneratedModules: WeakSet<Module>; buildTimeExecutedModules: WeakSet<Module>; emittedAssets: Set<string>; comparedForEmitAssets: Set<string>; fileDependencies: LazySet<string>; contextDependencies: LazySet<string>; missingDependencies: LazySet<string>; buildDependencies: LazySet<string>; compilationDependencies: { add: (item?: any) => LazySet<string> }; getStats(): Stats; createStatsOptions( optionsOrPreset: string | StatsOptions, context?: CreateStatsOptionsContext ): NormalizedStatsOptions; createStatsFactory(options?: any): StatsFactory; createStatsPrinter(options?: any): StatsPrinter; getCache(name: string): CacheFacade; getLogger(name: string | (() => string)): WebpackLogger; addModule( module: Module, callback: (err?: null | WebpackError, result?: Module) => void ): void; /** * Fetches a module from a compilation by its identifier */ getModule(module: Module): Module; /** * Attempts to search for a module by its identifier */ findModule(identifier: string): undefined | Module; /** * Schedules a build of the module object */ buildModule( module: Module, callback: (err?: null | WebpackError, result?: Module) => void ): void; processModuleDependencies( module: Module, callback: (err?: null | WebpackError, result?: Module) => void ): void; processModuleDependenciesNonRecursive(module: Module): void; handleModuleCreation( __0: HandleModuleCreationOptions, callback: (err?: null | WebpackError, result?: Module) => void ): void; addModuleChain( context: string, dependency: Dependency, callback: (err?: null | WebpackError, result?: Module) => void ): void; addModuleTree( __0: { /** * context string path */ context: string; /** * dependency used to create Module chain */ dependency: Dependency; /** * additional context info for the root module */ contextInfo?: Partial<ModuleFactoryCreateDataContextInfo>; }, callback: (err?: null | WebpackError, result?: Module) => void ): void; addEntry( context: string, entry: Dependency, optionsOrName: string | EntryOptions, callback: (err?: null | WebpackError, result?: Module) => void ): void; addInclude( context: string, dependency: Dependency, options: EntryOptions, callback: (err?: null | WebpackError, result?: Module) => void ): void; rebuildModule( module: Module, callback: (err?: null | WebpackError, result?: Module) => void ): void; finish(callback?: any): void; unseal(): void; seal(callback: (err?: null | WebpackError) => void): void; reportDependencyErrorsAndWarnings( module: Module, blocks: DependenciesBlock[] ): boolean; codeGeneration(callback?: any): void; processRuntimeRequirements(__0?: { /** * the chunk graph */ chunkGraph?: ChunkGraph; /** * modules */ modules?: Iterable<Module>; /** * chunks */ chunks?: Iterable<Chunk>; /** * codeGenerationResults */ codeGenerationResults?: CodeGenerationResults; /** * chunkGraphEntries */ chunkGraphEntries?: Iterable<Chunk>; }): void; addRuntimeModule( chunk: Chunk, module: RuntimeModule, chunkGraph?: ChunkGraph ): void; /** * If `module` is passed, `loc` and `request` must also be passed. */ addChunkInGroup( groupOptions: string | ChunkGroupOptions, module?: Module, loc?: SyntheticDependencyLocation | RealDependencyLocation, request?: string ): ChunkGroup; addAsyncEntrypoint( options: EntryOptions, module: Module, loc: DependencyLocation, request: string ): Entrypoint; /** * This method first looks to see if a name is provided for a new chunk, * and first looks to see if any named chunks already exist and reuse that chunk instead. */ addChunk(name?: string): Chunk; assignDepth(module: Module): void; assignDepths(modules: Set<Module>): void; getDependencyReferencedExports( dependency: Dependency, runtime: RuntimeSpec ): (string[] | ReferencedExport)[]; removeReasonsOfDependencyBlock( module: Module, block: DependenciesBlockLike ): void; patchChunksAfterReasonRemoval(module: Module, chunk: Chunk): void; removeChunkFromDependencies(block: DependenciesBlock, chunk: Chunk): void; assignRuntimeIds(): void; sortItemsWithChunkIds(): void; summarizeDependencies(): void; createModuleHashes(): void; createHash(): { module: Module; hash: string; runtime: RuntimeSpec; runtimes: RuntimeSpec[]; }[]; fullHash?: string; hash?: string; emitAsset(file: string, source: Source, assetInfo?: AssetInfo): void; updateAsset( file: string, newSourceOrFunction: Source | ((arg0: Source) => Source), assetInfoUpdateOrFunction?: AssetInfo | ((arg0?: AssetInfo) => AssetInfo) ): void; renameAsset(file?: any, newFile?: any): void; deleteAsset(file: string): void; getAssets(): Readonly<Asset>[]; getAsset(name: string): undefined | Readonly<Asset>; clearAssets(): void; createModuleAssets(): void; getRenderManifest(options: RenderManifestOptions): RenderManifestEntry[]; createChunkAssets(callback: (err?: null | WebpackError) => void): void; getPath( filename: string | ((arg0: PathData, arg1?: AssetInfo) => string), data?: PathData ): string; getPathWithInfo( filename: string | ((arg0: PathData, arg1?: AssetInfo) => string), data?: PathData ): { path: string; info: AssetInfo }; getAssetPath( filename: string | ((arg0: PathData, arg1?: AssetInfo) => string), data: PathData ): string; getAssetPathWithInfo( filename: string | ((arg0: PathData, arg1?: AssetInfo) => string), data: PathData ): { path: string; info: AssetInfo }; getWarnings(): WebpackError[]; getErrors(): WebpackError[]; /** * This function allows you to run another instance of webpack inside of webpack however as * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins * from parent (or top level compiler) and creates a child Compilation */ createChildCompiler( name: string, outputOptions?: OutputNormalized, plugins?: ( | ((this: Compiler, compiler: Compiler) => void) | WebpackPluginInstance )[] ): Compiler; executeModule( module: Module, options: ExecuteModuleOptions, callback: (err?: null | WebpackError, result?: ExecuteModuleResult) => void ): void; checkConstraints(): void; factorizeModule: { ( options: FactorizeModuleOptions & { factoryResult?: false }, callback: (err?: null | WebpackError, result?: Module) => void ): void; ( options: FactorizeModuleOptions & { factoryResult: true }, callback: ( err?: null | WebpackError, result?: ModuleFactoryResult ) => void ): void; }; /** * Add additional assets to the compilation. */ static PROCESS_ASSETS_STAGE_ADDITIONAL: number; /** * Basic preprocessing of assets. */ static PROCESS_ASSETS_STAGE_PRE_PROCESS: number; /** * Derive new assets from existing assets. * Existing assets should not be treated as complete. */ static PROCESS_ASSETS_STAGE_DERIVED: number; /** * Add additional sections to existing assets, like a banner or initialization code. */ static PROCESS_ASSETS_STAGE_ADDITIONS: number; /** * Optimize existing assets in a general way. */ static PROCESS_ASSETS_STAGE_OPTIMIZE: number; /** * Optimize the count of existing assets, e. g. by merging them. * Only assets of the same type should be merged. * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT: number; /** * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY: number; /** * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE: number; /** * Add development tooling to assets, e. g. by extracting a SourceMap. */ static PROCESS_ASSETS_STAGE_DEV_TOOLING: number; /** * Optimize the count of existing assets, e. g. by inlining assets of into other assets. * Only assets of different types should be inlined. * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE: number; /** * Summarize the list of existing assets * e. g. creating an assets manifest of Service Workers. */ static PROCESS_ASSETS_STAGE_SUMMARIZE: number; /** * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_HASH: number; /** * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. */ static PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER: number; /** * Analyse existing assets. */ static PROCESS_ASSETS_STAGE_ANALYSE: number; /** * Creating assets for reporting purposes. */ static PROCESS_ASSETS_STAGE_REPORT: number; }